Error Handling
Robust programs anticipate failure. JavaScript's try/catch/finally blocks, custom error classes, and async error patterns let you handle failures gracefully rather than crashing silently or unexpectedly.
How does try...catch work in JavaScript?
Wrap code that might fail in try { … }. If an error is thrown, execution jumps to catch (error) { … }, where you can handle it, and finally { … } runs either way. Throw your own errors with throw new Error("message"). For async code, use try/catch around await, or .catch() on promises.
try {
const data = JSON.parse(input);
} catch (error) {
console.error("Invalid JSON:", error.message);
} finally {
hideSpinner();
}
class ValidationError extends Error {
constructor(field) { super(`${field} is invalid`); this.name = "ValidationError"; }
}try / catch / finally
try { }— Wrap code that might throw an errorcatch (err) { }— Runs if try throws — err is the Error objectfinally { }— Always runs, whether or not an error occurred. Good for cleanup.throw expression— Manually throw any value (usually an Error instance)
Built-in Error Types
ErrorBase class for all errorsTypeErrorWrong type — e.g. calling null as a functionReferenceErrorAccessing an undeclared variableSyntaxErrorInvalid JavaScript syntax (parse-time)RangeErrorValue out of valid range — e.g. new Array(-1)URIErrorMalformed URI in encodeURI / decodeURICustom Error Classes
Extend the built-in Error class to create domain-specific errors. This lets you distinguish error types with instanceofand carry structured context data.
Async Error Handling
async/await + try/catch
Wrap await calls in try/catch for clean, readable async error handling.
Promise .catch()
Chain .catch() on promise chains. Always return or re-throw inside.
Unhandled Rejections
Use window.addEventListener('unhandledrejection') globally to catch missed rejections.
Common Pitfalls
Interactive Examples
Code Editor
<input id="json" value='{"name": "Ada"'>
<button id="parse">Parse JSON</button>
<pre id="out"></pre>Preview
Error handling — step by step
try / catch / finally structure
Code in try runs normally. If any statement throws, execution jumps immediately to catch — skipping the rest of try. The catch block receives the Error object. finally always runs, whether or not an error was thrown — ideal for cleanup like closing connections or releasing locks, regardless of outcome.
🎯 Quick Check
What happens if an async function throws an error that is never caught?
JavaScript Error Handling: summary
Key points
- Catch errors where you can actually do something useful about them, not everywhere.
- Always throw
Errorobjects (not strings) so you get a stack trace. try/catchdoesn't catch errors in callbacks that run later, such assetTimeout; handle those inside the callback.- Unhandled promise rejections need
.catch()ortry/await.
Frequently asked questions
›Does try/catch work with async code?
With async/await, yes: put the await inside try. With plain promises, use .catch().
›Should I catch every error?
No. Swallowing errors hides bugs. Catch errors you can recover from or report, and let unexpected ones surface.