Difficulty: Beginner
How does error handling work in JavaScript? Explain try/catch/finally, the built-in error types and custom error classes.
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.
try block runs.catch (err) and the rest of try is skipped.finally runs after try or catch, even if they return or rethrow.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.
| 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.
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.
try/catch around setTimeout(() => { throw ... }) does not catch the error, because the callback runs later on a different call stack..catch() or await inside try. A missing await means the rejection escapes the try block.process.on('unhandledRejection') for logging, but fix the source.next(err); Express 5 forwards rejected promises from handlers automatically.Error objects, never strings: throw 'oops' has no stack trace.catch {}; at minimum log them.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.
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 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.
try/catch/finally, Error Types, Custom Errors, Error Cause, Async Error Handling