try...catch...finally

Runs code that may throw, handling errors and optionally running cleanup.

Since ES3 Spec ↗

Syntax

try {
  // ...
} catch (err) {
  // ...
} finally {
  // ...
}

Examples

try {
  JSON.parse("{ bad json");
} catch (e) {
  console.log("caught:", e.name);
}
Output
caught: SyntaxError
function run() {
  try {
    return "from try";
  } finally {
    console.log("finally ran");
  }
}
console.log(run());
Output
finally ran
from try
// Optional catch binding (ES2019)
try {
  throw new Error("x");
} catch {
  console.log("handled");
}
Output
handled

Notes

- `finally` always runs, whether or not an exception was thrown, even after a `return`. - The catch binding is optional since ES2019 when the error is unused. - Avoid catching errors you cannot handle; let them propagate.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also