Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The try...catch...finally statement

Reference for JavaScript try...catch...finally: catching exceptions, optional catch binding, finally cleanup, rethrowing and how it works with async code.

try...catch...finally runs a block of code and lets you react if it throws. The try block holds the code that might fail. If an exception is thrown inside it, the rest of the block is skipped and the catch block runs with the thrown value. The finally block runs afterwards in every case, whether the code succeeded, threw, or returned early.

You need catch, finally, or both after a try.

JavaScript
try {
  riskyWork();
} catch (error) {
  console.error(error.message);
} finally {
  cleanUp();
}

Try it

JS Catching a failed parse

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS finally and return

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
try { statements }
catch (exceptionVar) { statements }
finally { statements }

try { statements } catch { statements }   // no binding
try { statements } finally { statements }
Part Description
exceptionVar Receives the thrown value. It can be a destructuring pattern, and is scoped to the catch block. It may be omitted.
finally Always runs after try and catch, even after return, break or continue.

Usage notes

  • Only synchronous errors. A try block catches exceptions thrown while it runs. Errors in later callbacks (setTimeout, event handlers) are outside it.
  • Async code. Inside an async function, await a promise within try to catch its rejection. Without await, the rejection escapes the block.
  • The thrown value is not always an Error. Code can throw strings or any value, so check err instanceof Error when you need message or stack.
  • Catch what you can handle. Catching everything hides bugs. Inspect the error and rethrow the rest with throw err.
  • finally overrides. A return or throw inside finally replaces whatever the try or catch block produced. Use finally for cleanup (closing, unlocking, hiding a spinner), not for return values.
  • Scope. Variables declared with let or const inside try are not visible in catch or finally; declare them before the try.
  • Stack overflow and out-of-memory conditions can often be caught too, but the program may be in a poor state afterwards.
  • Performance. Modern engines optimize functions that contain try; do not avoid it for speed.

Browser support

try...catch...finally works everywhere. Optional catch binding (catch { }) is supported by all current browsers.