try ... catch ... finally (Statement)

A mechanism for attempting to execute some potentially problematic code with a means of catching the exception and continuing execution.

Availability:

ECMAScript edition - 3
JavaScript - 1.5
JScript - 5.0
Internet Explorer - 5.0
Netscape - 6.0

This was introduced in JavaScript 1.4 and JScript version 5.0. The intention is to provide a way to execute a section of code in the try block and then if it has a problem, some recovery action can trap the error and handle it gracefully.

There are three basic sections.

The try statement is followed by a block of code enclosed in braces that may be problematic. Indeed, the problems may not be script-based errors but may be the result of testing for some condition. That may lead to a custom exception being thrown.

If an exception of any kind happens in the try block, execution is immediately passed to the catch() function following.

The catch function is passed an Error object containing details of the kind of exception that has occurred.

When the catch function completes, execution drops into the block of code associated with the finally statement. In the case of the try block not having any exceptional behavior, at the end of that block execution also drops into the finally code block, bypassing the catch function altogether. So the finally code gets executed always after the try block.

You might use the finally block to tidy up or discard some unwanted objects.

In the example, the try block makes sure two values are presented in the correct order. If they are not in the right order, an exception is thrown and during the exception handling, they are swapped over. We put up an alert and set a flag that is presented in the output just to be sure it really happened like that.

Warnings:

Example code:

   <HTML>
   <HEAD>
   </HEAD>
   <BODY>
   <SCRIPT>
   testThrow(100, 200);
   testThrow(300, 100);
   function testThrow(arg1, arg2)
   {
      var switched = "NO";
   
      // Force an error condition
      try
      {
         if(arg1 < arg2)
         {
            throw "Wrong order";
         }
      }
      catch(myErr)
      {
         alert(myErr);
         var temp = arg1;
         arg1 = arg2;
         arg2 = temp;
         switched = "YES"
      }
      finally
      {
         document.write("Biggest : "  + arg1 + "<BR>");
         document.write("Smallest : " + arg2 + "<BR>");
         document.write("Switched : " + switched + "<BR>");
         document.write("<BR>");
      }
   }
   </SCRIPT>
   </BODY>
   </HTML>

See also:catch( ... ), Error object, EvalError object, Exception handling, finally ..., RangeError object, ReferenceError object, SyntaxError object, throw, TypeError object, URIError object

Cross-references:

ECMA 262 edition 2 - section - 7.4.3

ECMA 262 edition 3 - section - 7.5.2

ECMA 262 edition 3 - section - 12.14