try/catch/finally

The try/catch/finally statement is JavaScript’s exception-handling mechanism. The try clause of this statement simply defines the block of code whose exceptions are to be handled. The try block is followed by a catch clause, which is a block of statements that are invoked when an exception occurs anywhere within the try block. The catch clause is followed by a finally block containing cleanup code that is guaranteed to be executed, regardless of what happens in the try block. Both the catch and finally blocks are optional, but a try block must be accompanied by at least one of these blocks. The try, catch, and finally blocks all begin and end with curly braces. These are a required part of the syntax and cannot be omitted, even if the clause contains only a single statement. Like the throw statement, the try/catch/finally statement is standardized by ECMAScript v3 and implemented in JavaScript 1.4.

The following code illustrates the syntax and purpose of the try/catch/finally statement. In particular, note that the catch keyword is followed by an identifier in parentheses. This identifier is like a function argument. It names a local variable that exists only within the body of the catch block. JavaScript assigns whatever exception object or value was thrown to this variable:

try { // Normally, this code runs from the top of the block to the bottom // without problems. But it can sometimes throw an exception, // either directly, with a throw statement, or ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.