Core Language

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 error
  • catch (err) { } — Runs if try throws — err is the Error object
  • finally { } — 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 errors
TypeErrorWrong type — e.g. calling null as a function
ReferenceErrorAccessing an undeclared variable
SyntaxErrorInvalid JavaScript syntax (parse-time)
RangeErrorValue out of valid range — e.g. new Array(-1)
URIErrorMalformed URI in encodeURI / decodeURI

Custom 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.

class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
// Catch specific type:
if (e instanceof ValidationError) {
showFieldError(e.field, e.message);
}
Hierarchy: Create a base AppError, then extend it into ValidationError, NetworkError, AuthError, etc.
Error codes: Add a code property (e.g. 'NOT_FOUND', 'UNAUTHORIZED') for programmatic handling.
Context: Attach structured data to the error for logging and debugging.
Re-throw: If you can't handle an error in a catch block, re-throw it for a higher-level handler.

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.

Best practice: Never let a rejected promise go unhandled. Always add .catch() or use try/catch inside async functions. For Express/Node apps, use a central error-handling middleware as the last resort.

Common Pitfalls

Swallowing errors silently (empty catch blocks)
Log or re-throw — silent catches hide bugs
Throwing non-Error values (throw 'message')
Always throw Error instances so you get a stack trace
Catching too broadly — one giant try around everything
Use granular try/catch blocks around specific risky operations
Not handling Promise rejections
Every async function call should be awaited inside try/catch or have .catch()

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

1 / 4
1

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.

1 of 4
⚠️finally does not suppress errors
A return or throw inside a finally block overrides the pending return or throw from try/catch. This can silently swallow errors if you accidentally throw inside finally. Keep finally minimal — cleanup only, no returns or throws.

🎯 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 Error objects (not strings) so you get a stack trace.
  • try/catch doesn't catch errors in callbacks that run later, such as setTimeout; handle those inside the callback.
  • Unhandled promise rejections need .catch() or try/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.