JavaScript tutorial:
try...catch statement

 

The try implements error handling for JavaScript.

Syntax

try
  tryStatement
catch(exception)
  catchStatement

The try...catch statement syntax has these parts:

Part

Description

tryStatement

Statement where an error can occur. Can be a compound statement.

exception

Any variable name. The initial value of exception is the value of the thrown error.

catchStatement

Statement to handle errors occurring in the associated tryStatement. Can be a compound statement.

Return value

None

Example

The try...catch 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, JavaScript simply provides its normal error message to a user, as if there was no error handling.

The tryStatement argument contains code where an error can occur, while catchStatement contains the code to handle any error that does occur. If an error occurs in the tryStatement, program control is passed to catchStatement for disposition. The initial value of exception is the value of the error that occurred in tryStatement.

If the error cannot be handled in the catchStatement associated with the tryStatement where the error occurred, use the throw statement to propagate, or rethrow, the error to a higher-level error handler.

The following example throws an error based on a passed-in value. It then illustrates how that error is handled in a hierarchy of try...catch statements:

function TryCatchDemo(x)
{
try {
try {
if (x == 0) // Evalute argument.
throw "x equals zero"; // Throw an error.
else
throw "x does not equal zero"; // Throw a different error.
}
catch(e) { // Handle "x = 0" errors here.
if (e == "x equals zero") // Check for an error handled here.
return(e + " handled locally."); // Return object error message.
else // Can't handle error here.
throw e; // Rethrow the error for next
} // error handler.
}
catch(e) { // Handle other errors here.
return(e + " handled higher up."); // Return error message.
}
}
document.write(TryCatchDemo(0));
document.write(TryCatchDemo(1));

To run the code, paste it into JavaScript Editor, and click the Execute button.

See also: throw Statement