Error Handling (try/catch/finally)

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

TypeTypical cause
ErrorGeneric base class
TypeErrorCalling a non-function, reading a property of undefined
ReferenceErrorUsing an undeclared variable or a let in its TDZ
SyntaxErrorBad code at parse time, or JSON.parse('{bad') at runtime
RangeErrorInvalid length, toFixed(200), too much recursion in some engines
URIErrorMalformed decodeURIComponent input
AggregateErrorSeveral 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

Practical guidelines

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

Common follow-up questions

Interview tips

Concepts covered

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

More JavaScript Interview questions