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.
try { riskyWork(); } catch (error) { console.error(error.message); } finally { cleanUp(); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
tryblock catches exceptions thrown while it runs. Errors in later callbacks (setTimeout, event handlers) are outside it. - Async code. Inside an
asyncfunction,awaita promise withintryto catch its rejection. Withoutawait, the rejection escapes the block. - The thrown value is not always an
Error. Code can throw strings or any value, so checkerr instanceof Errorwhen you needmessageorstack. - Catch what you can handle. Catching everything hides bugs. Inspect the error and rethrow the rest with
throw err. finallyoverrides. Areturnorthrowinsidefinallyreplaces whatever thetryorcatchblock produced. Usefinallyfor cleanup (closing, unlocking, hiding a spinner), not for return values.- Scope. Variables declared with
letorconstinsidetryare not visible incatchorfinally; declare them before thetry. - 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.
Related
throw,returnError,Promise.prototype.catch()- Lesson: Errors, Async and await