# Error Handling (try/catch/finally)

> How does error handling work in JavaScript? Explain try/catch/finally, the built-in error types and custom error classes.

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-error-handling
Last updated: 2026-11-28

Difficulty: Beginner

## Question

How does error handling work in JavaScript? Explain try/catch/finally, the built-in error types and custom error classes.

## Answer

JavaScript handles runtime errors with `try...catch...finally`: code that might throw goes in `try`, `catch` receives the thrown value, and `finally` runs no matter what, which makes it the place for cleanup. You raise errors with `throw`, ideally throwing `Error` objects (or subclasses) so you get a `message`, a `name` and a stack trace. Custom error classes extend `Error` so callers can tell failure kinds apart with `instanceof`.

### How try/catch/finally executes

1. The `try` block runs.
2. If something throws, execution jumps straight to `catch (err)` and the rest of `try` is skipped.
3. `finally` runs after `try` or `catch`, even if they `return` or rethrow.
4. If `finally` itself has a `return`, it overrides any earlier return or thrown error, which silently swallows exceptions. Never return from `finally`.

The catch binding is optional since ES2019: `catch { ... }` when you do not need the error.

### Built-in error types

| Type | Typical cause |
| --- | --- |
| `Error` | Generic base class |
| `TypeError` | Calling a non-function, reading a property of `undefined` |
| `ReferenceError` | Using an undeclared variable or a `let` in its TDZ |
| `SyntaxError` | Bad code at parse time, or `JSON.parse('{bad')` at runtime |
| `RangeError` | Invalid length, `toFixed(200)`, too much recursion in some engines |
| `URIError` | Malformed `decodeURIComponent` input |
| `AggregateError` | Several errors at once, for example from `Promise.any` |

`try/catch` only catches runtime errors in its own synchronous execution. A SyntaxError in the same script cannot be caught because the script never runs.

### Custom errors and error cause

Extend `Error`, call `super(message)`, and set `this.name`. Add fields like `statusCode` or `code` so a central handler can map the error to an HTTP response. Since ES2022 you can pass `{ cause }` as the second argument: `new PaymentError('Charge failed', { cause: err })`. This wraps a low-level error without losing the original, and Node and browsers print the cause chain in stack traces.

### Async code is where people get it wrong

- A `try/catch` around `setTimeout(() => { throw ... })` does not catch the error, because the callback runs later on a different call stack.
- With promises, use `.catch()` or `await` inside `try`. A missing `await` means the rejection escapes the `try` block.
- Unhandled promise rejections crash the process by default since Node 15. Register `process.on('unhandledRejection')` for logging, but fix the source.
- In Express 4, async route errors need to be passed to `next(err)`; Express 5 forwards rejected promises from handlers automatically.

### Practical guidelines

- Throw `Error` objects, never strings: `throw 'oops'` has no stack trace.
- Catch only what you can handle. Rethrow everything else.
- Do not swallow errors with an empty `catch {}`; at minimum log them.
- Validate input early and fail with a clear message instead of letting a TypeError surface three functions later.
- In production, centralise handling (an Express error middleware, a React error boundary) and send errors to a tracker like Sentry.

**How a thrown error unwinds the stack. Move the try/catch, toggle finally, or let it go uncaught under Tweak.**

1. **throw abandons the function**: Execution jumps out of c().
2. **Unwinding**: Each caller without a catch is abandoned in turn.
3. **finally always runs**: Cleanup runs whether or not the error is caught.
4. **catch stops it**: The program continues normally after the catch.

## Code examples

### Custom error classes with cause

```
class AppError extends Error {
  constructor(message, { statusCode = 500, cause } = {}) {
    super(message, { cause });
    this.name = this.constructor.name;
    this.statusCode = statusCode;
  }
}
class ValidationError extends AppError {
  constructor(field) {
    super(`Invalid value for ${field}`, { statusCode: 400 });
    this.field = field;
  }
}

function parseOrder(json) {
  try {
    return JSON.parse(json);
  } catch (err) {
    throw new AppError('Order payload is not valid JSON', { statusCode: 400, cause: err });
  }
}

try {
  parseOrder('{amount: 100}');
} catch (err) {
  console.log(err.name, err.statusCode, err.message);
  console.log('cause:', err.cause.name);
  console.log(err instanceof AppError, err instanceof ValidationError);
}
```

Subclasses give each failure a name and extra fields, and the ES2022 cause option keeps the original SyntaxError attached for debugging.

### finally runs even after return

```
function withLock() {
  console.log('lock acquired');
  try {
    return 'result';
  } finally {
    console.log('lock released');
  }
}
console.log(withLock());

function swallow() {
  try {
    throw new Error('lost');
  } finally {
    return 'finally wins'; // anti-pattern: hides the error
  }
}
console.log(swallow());
```

finally runs before the function actually returns. A return inside finally overrides the thrown error, which is why it is considered a bug.

### Async errors need await

```
async function chargeCard() {
  throw new Error('Gateway timeout');
}

async function checkout() {
  try {
    await chargeCard(); // without await, the catch below never runs
  } catch (err) {
    console.log('Handled:', err.message);
  }
}
checkout();

try {
  setTimeout(() => { /* throw here would NOT be caught */ }, 0);
} catch { /* never reached for async throws */ }
```

try/catch only sees errors on the current call stack. await brings the rejection back into it; a setTimeout callback runs on a fresh stack.

## Key points

- finally always runs; never return from it
- Throw Error objects, not strings, to keep stack traces
- Extend Error and set name for custom error types
- Use { cause } (ES2022) to wrap low-level errors
- try/catch does not catch errors thrown later in callbacks; await promises inside try

## Common follow-up questions

- How do you handle errors in Promise.all when one promise rejects?
- What is a React error boundary and what can it not catch?
- How would you build centralised error handling in an Express API?
- What happens to an unhandled promise rejection in Node.js?

## Interview tips

- Walk through the execution order including the finally-with-return edge case
- Show a custom error class with a statusCode; it maps directly to backend work
- Mention the async pitfall (missing await, setTimeout) to show real debugging experience

## Concepts covered

try/catch/finally, Error Types, Custom Errors, Error Cause, Async Error Handling

Previous: [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread) · Next: [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions)
- [Template Literals & String Interpolation](https://www.internhack.in/learn/interview/javascript-interview/js-template-literals)
- [null vs undefined](https://www.internhack.in/learn/interview/javascript-interview/js-null-undefined)
- [JSON: parse, stringify & Common Pitfalls](https://www.internhack.in/learn/interview/javascript-interview/js-json-parse-stringify)
- [Closures & Lexical Scope](https://www.internhack.in/learn/interview/javascript-interview/js-closures-interview)
- [Hoisting & Temporal Dead Zone](https://www.internhack.in/learn/interview/javascript-interview/js-hoisting-interview)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
