JavaScript try...catch Statement
The try...catch statement runs code that might throw an error and lets you handle the error in a catch block instead of stopping the script. An optional finally block always runs.
Description
The try...catch statement marks a block of code to try, and a catch block that runs if any statement in it throws an exception. Instead of the error stopping the script, it is passed to the catch block, where you can log it, show a message or recover. An optional finally block runs afterwards in every case, which is useful for clean-up such as hiding a loading spinner.
The catch block receives the thrown value, usually an Error object with name and message properties. You can leave out the parameter, as in catch { ... }, if you don't need it. You need at least one of catch or finally.
With async functions, try...catch also catches rejected promises that you await. It does not catch errors thrown later in callbacks, such as inside a setTimeout() callback started in the try block. Only catch errors you can handle; rethrow the rest with throw.
Syntax
try {
tryStatements
} catch (error) {
catchStatements
} finally {
finallyStatements
}Example
Browser Support
The following information will show you the current browser support for the try...catch statement. Hover over a browser icon to see the version that first introduced support for this statement.
Desktop





Tablets & Mobile





