Implements error handling for JScript.
try { tryStatements} catch(exception){ catchStatements} finally { finallyStatements}
The try...catch…finally statement provides a way to handle some or all of the possible errors that may occur in a given block of code, while still running code. If errors occur that the programmer has not handled, JScript simply provides its normal error message to a user, as if there was no error handling.
The tryStatements contain code where an error can occur, while catchStatements contain the code to handle any error that does occur. If an error occurs in the tryStatements, program control is passed to catchStatements for processing. The initial value of exception is the value of the error that occurred in tryStatements. If no error occurs, catchStatements are never executed.
If the error cannot be handled in the catchStatements associated with the tryStatements where the error occurred, use the throw statement to propagate, or rethrow, the error to a higher-level error handler.
After all statements in tryStatements have been executed and any error handling has occurred in catchStatements, the statements in finallyStatements are unconditionally executed.
Notice that the code inside finallyStatements is executed even if a return statement occurs inside the try or catch blocks, or if the catch block re-throws the error. finallyStatments are guaranteed to always run, unless an unhandled error occurs (for example, causing a run-time error inside the catch block).
The following example shows how JScript exception handling works.
try { print("Outer try running.."); try { print("Nested try running..."); throw "an error"; } catch(e) { print("Nested catch caught " + e); throw e + " re-thrown"; } finally { print("Nested finally is running..."); } } catch(e) { print("Outer catch caught " + e); } finally { print("Outer finally running"); } // Change this for Windows Script Host to say WScript.Echo(s) function print(s){ document.write(s); }
This produces the following output:
Outer try running.. Nested try running... Nested catch caught an error Nested finally is running... Outer catch caught an error re-thrown Outer finally running