The JavaScript try...catch statement
The try...catch statement runs code that might fail and catches any error instead of letting it crash the program. try { risky(); } catch (err) { handle(err); }. An optional finally block runs either way. It's essential around JSON.parse(), fetch() and other operations that can throw.
Overview
try...catch is how you handle errors gracefully. Code in the try block runs normally; if anything in it throws an error, execution jumps straight to the catch block, which receives the error object. Instead of an uncaught error crashing your script, you get a chance to log it, show a message, or fall back to a default.
You reach for it around anything that can legitimately fail: parsing untrusted JSON with JSON.parse(), network calls with fetch(), accessing things that might not exist. The optional finally block runs whether or not an error happened — perfect for cleanup like hiding a loading spinner or closing a resource. You can also raise your own errors with throw new Error("message").
With async/await, try...catch is how you handle rejected promises — a major reason async/await is nicer than raw .then() chains. One piece of advice: don't wrap everything in a giant try and swallow errors silently. Catch where you can actually do something useful, and at minimum log what went wrong so problems don't disappear.
Syntax
try {
// code that might throw
} catch (error) {
// handle the error
} finally {
// always runs (cleanup)
}
throw new Error("Something went wrong");
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const inputs = ['{"ok":true}', 'not json'];
const results = [];
for (const text of inputs) {
try {
const data = JSON.parse(text);
results.push('parsed: ' + JSON.stringify(data));
} catch (err) {
results.push('failed: ' + err.message);
}
}
document.getElementById('out').textContent = results.join('\n');
</script>
Best practices
- Wrap operations that can genuinely fail — JSON.parse(), fetch(), risky access.
- Use
finallyfor cleanup that must run regardless of success or failure. - Don't swallow errors silently — at least log them so failures are visible.
- With async/await, use
try...catchto handle rejected promises.
Frequently asked questions
How do I handle errors in JavaScript?
try block and handle failures in catch (err). Add finally for cleanup that always runs.What does the finally block do?
try/catch whether or not an error occurred — ideal for cleanup like closing connections or hiding spinners.How do I throw my own error?
throw new Error("message"). It stops execution and jumps to the nearest catch.How do I catch errors with async/await?
await calls in try...catch — a rejected promise throws into the catch block.