Error Handling

Dealing with things that go wrong in your code on purpose, instead of letting the program crash.

What is it?

Sometimes code can't do its job: a network request fails, a file is missing, a value isn't what you expected. That throws an error, and if nothing handles it, the program crashes. try/catch lets you say "try this, and if it fails, run this instead of crashing."

Explain like I'm 10

It's like a safety net under a tightrope walker. You still attempt the risky move (the try), but if it goes wrong, the net (the catch) stops it becoming a disaster.

Examples

try / catch / finally

function parseUserAge(input) {
  try {
    const age = JSON.parse(input);
    if (typeof age !== "number") {
      throw new Error("Age must be a number");
    }
    return age;
  } catch (error) {
    console.log("Invalid input:", error.message);
    return null;
  } finally {
    console.log("Finished attempting to parse.");
  }
}

A custom error class

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

function setAge(age) {
  if (age < 0) {
    throw new ValidationError("Age can't be negative");
  }
  return age;
}

try {
  setAge(-5);
} catch (error) {
  if (error instanceof ValidationError) {
    console.log("Validation failed:", error.message);
  } else {
    throw error; // an error we didn't expect — let it propagate
  }
}

Custom error classes let a catch block tell kinds of failure apart with instanceof instead of treating every error the same.

How it works

When code in try throws (on its own from a failing operation, or via throw), JavaScript stops that block and jumps to catch, skipping the rest of try. The optional finally block runs afterward whatever happened, which suits cleanup that must always run.

Why does it exist?

Without it, one unexpected failure anywhere would crash the whole program. try/catch keeps a failure contained to the operation that caused it, lets you respond sensibly (retry, show a message, use a default), and keeps the rest running.

When to use it

Use try/catch around operations that can realistically fail and that you want to handle gracefully: parsing untrusted data, network requests (often with async/await), or anything whose failure shouldn't crash the app.

When not to use it

Don't add try/catch "just in case" when there's no realistic failure or nothing sensible to do in the catch. Silently swallowing errors hides real bugs. And don't use exceptions for normal control flow (like checking if a key exists) when a simple if will do.

Common mistakes

  • Catching an error and doing nothing with it (an empty catch block), which hides bugs instead of fixing them.

  • Forgetting that catch only catches errors thrown synchronously inside the try. A callback or an unawaited promise inside it can still fail unnoticed.

  • Throwing plain strings or objects instead of an Error (or subclass), losing useful information like a stack trace.

Practice exercises

  1. Easy:

    Write a function that safely divides two numbers, throwing an error if the divisor is 0, and catching it to return null instead of crashing.

  2. Medium:

    Create a custom error class ValidationError extends Error and throw/catch an instance of it.

  3. Hard:

    Write an async function that retries a failing operation up to 3 times before giving up, using try/catch inside a loop.

Interview questions

Does `finally` still run if the `try` block contains a `return` statement?

Yes. finally always runs before the function returns, whether try finished normally, threw an error that was caught, or hit a return. Only a crash of the whole process can skip it.

Predict the output: `function f() { try { return 1; } finally { return 2; } } console.log(f());`

2. A return in finally overrides whatever try (or catch) was about to return, and even an error that was about to propagate. It's a known footgun, so avoid returning from finally.

If an error is already propagating out of a `catch` block, and the paired `finally` block also throws, which error wins?

The one from finally. Like a return in finally, a throw there replaces the error already on its way out. The original error is lost unless you saved it first.

Can you write `try { ... } finally { ... }` with no `catch` at all? What happens to an error thrown inside `try` in that case?

Yes. finally still runs for cleanup, but with no catch the error keeps propagating upward afterward. try/finally guarantees cleanup; it doesn't contain the error.

What is the "optional catch binding" syntax (`catch { ... }` with no parameter), and when is it useful?

It lets you write catch without naming the error, for when you only need to know something failed, not what. It avoids an unused variable that the older syntax required.

Why is throwing a plain string or plain object considered worse practice than throwing an `Error` instance?

An Error captures a stack trace and a consistent message/name shape when it's created, which is invaluable for finding where and why something failed. A thrown string or plain object has none of that, so the call-site information is lost.

What is `error.stack`, and where does its content actually come from?

A string filled in automatically when an Error (or subclass) is constructed, showing the function calls active at that moment (the call stack). That's why creating the Error, not throwing it, is what captures the trace.

What does the `cause` option in `new Error(message, { cause: originalError })` let you do?

It attaches an underlying error to a new, higher-level one. For example, wrap a low-level network error in a clearer 'Failed to load user' error and keep the original available via .cause instead of discarding it.

Inside an `async` function's `try` block, does `catch` reliably handle a promise that's created but never `await`ed?

No. try/catch only catches a rejection where you await that promise. A promise started without being awaited (or returned) can reject later, outside the try/catch, and becomes an unhandled rejection.

Why doesn't a `try/catch` wrapped around `setTimeout(() => { throw new Error("boom"); }, 0)` catch that thrown error?

The try/catch has already finished running long before the timer callback runs on a later turn of the event loop. When the error is thrown, no try/catch is still active. Catch it inside the callback itself.

How do you correctly handle an error from an older, callback-style asynchronous function (not one that returns a promise)?

Check the error argument inside the callback (the 'error-first callback' convention). A try/catch around the outer call can't catch an error raised later, in a callback that runs on a different turn of the event loop.

What's the danger of an empty `catch` block that does nothing with the error it caught?

It silently swallows real failures. The program carries on as if nothing went wrong, hiding bugs that would otherwise show up as a crash or a log, and making the eventual symptom much harder to trace to its cause.

How do you handle several different kinds of errors differently inside a single `catch` block?

Check the error's type with instanceof, from most to least specific (a subclass is also an instance of its parent), and branch. JavaScript has no multiple typed catch clauses, so this is the idiomatic replacement.

What are some of JavaScript's built-in `Error` subtypes, and what typically triggers each one?

TypeError: using a value in a way its type doesn't support (calling something that isn't a function, or reading a property of null/undefined). RangeError: a value outside the allowed range (like an invalid array length). ReferenceError: a name that doesn't exist. SyntaxError: malformed code, or malformed input to something like JSON.parse.

Predict what each of these throws: `null.foo`, referencing an undeclared variable, and `JSON.parse("{bad")`.

null.foo throws a TypeError (you can't read a property of null). An undeclared variable throws a ReferenceError. JSON.parse("{bad") throws a SyntaxError because the text isn't valid JSON. Knowing which is which lets a catch respond appropriately.

When should you rethrow an error you just caught, instead of handling it right there?

When the current code can't do anything useful about the failure. Logging and swallowing it would hide the problem from the layer that could handle it, so let it keep propagating.

When is throwing an exception the right call for invalid input, versus just returning early with an `if` check or an error code?

Throw for unexpected situations the caller can't easily check for ahead of time (a network failure, a corrupt file). For normal, expected conditions the caller should check routinely (an empty search result, a missing optional field), a return value or early if/return is clearer and cheaper.

How does extending `Error` correctly (`class ValidationError extends Error { constructor(msg) { super(msg); ... } }`) preserve `instanceof` checks?

super(message) runs Error's constructor, which sets up the prototype chain through Error.prototype. Then error instanceof ValidationError and error instanceof Error both return true. Skipping super() (or not extending Error) breaks that chain.

Is it possible for `error instanceof MyCustomError` to fail even when the error really was thrown as `new MyCustomError(...)`?

Yes, in some unusual setups. For example, transpiling class syntax to an older JS target without special handling for extending built-ins can break the prototype chain, because native Error extension relies on engine behavior a naive transpile doesn't reproduce.

What's an "unhandled promise rejection", and how is it different from an uncaught synchronous exception?

A promise that rejected with no .catch() (or awaiting try/catch) attached. An uncaught synchronous exception usually stops execution right there. An unhandled rejection is detected asynchronously, and the browser or Node reports it separately, sometimes well after it happened.

How would you set up a last-resort handler to catch errors that slipped past every other `try/catch` in an app?

In a browser, listen for the global error event (or set window.onerror) for uncaught exceptions, and unhandledrejection for unhandled promise rejections. In Node.js, use process.on("uncaughtException", ...) and process.on("unhandledRejection", ...). These are a last-resort net for logging and cleanup, not a substitute for handling errors near where they happen.

If every code path inside a `try` block ends in a `return`, does the paired `finally` block still get a chance to run before the function actually returns?

Yes. finally always runs right before control leaves the function, whichever return was taken in try. Guaranteeing cleanup however the block exits is its whole purpose.

What's the tradeoff between wrapping a `try/catch` around each iteration of a loop individually versus wrapping the entire loop in one `try/catch`?

Per-iteration catching lets the loop keep processing the other items when one fails, for slightly more code. Wrapping the whole loop is simpler but stops everything at the first failure, so one bad item can block all the rest.

Why is it risky to rely on one giant `try/catch` around an entire application as the main error-handling strategy?

It catches and quietly swallows many unrelated failures in one place, far from where they happened and with little context to respond. Real bugs hide behind a generic 'something went wrong' instead of being handled or surfaced near their source.

Can a single `try` block have multiple `catch` clauses for different error types, the way some other languages allow?

No. JavaScript allows one catch per try. Tell error types apart inside that catch, usually with instanceof.

What happens if the code inside a `catch` block itself throws a new error?

The new error propagates upward like any thrown error. The same catch doesn't catch it; you need an enclosing try/catch to handle failures during error handling.

Is there a meaningful runtime performance penalty to wrapping code in `try/catch` in modern JavaScript engines?

Not really, in the common case. Modern engines optimize try/catch well, and the old advice to avoid it for speed is outdated. Use it where it adds clarity and safety.

Why should error messages meant for logging or debugging often be different from what's shown directly to an end user?

A log message can include technical detail (stack traces, internal IDs, exact reasons) that helps diagnosis but is meaningless or risky (it can leak internals) to show users. Users need a simpler, actionable message.

What's the benefit of a function throwing early ("failing fast") on invalid input, instead of letting bad data quietly propagate deeper into the program?

It surfaces the problem at its source, with a clear message and a stack trace pointing at the real cause. Otherwise the program keeps going with bad data and fails confusingly much later, somewhere unrelated to the original problem.

How would you write a function that retries a flaky operation up to a fixed number of times before finally giving up?

Loop up to the retry limit with try/catch around each attempt. On success, return right away. On failure, catch and try again, or once the limit is reached, rethrow the last error (or return an explicit failure) instead of giving up silently.