Skip to the page

Modules, errors and memory · mid

Errors: types, try/catch/finally and cause

JavaScript errors are objects (TypeError, ReferenceError, RangeError, SyntaxError and others) thrown with throw and caught by the nearest try/catch on the current call stack; finally always runs, so good handling means throwing real Error objects with a cause, catching only where you can act, and never swallowing errors silently.

The notes

What you must know

  • Built-in types: Error, TypeError (wrong type, calling non-functions), ReferenceError (unknown or TDZ variable), RangeError (bad length, stack overflow), SyntaxError, URIError, EvalError, AggregateError (Promise.any).
  • Throw Error objects, not strings, so you get a stack trace and instanceof works. Custom errors: class ValidationError extends Error, and set this.name.
  • new Error(message, { cause }) (ES2022) wraps a lower-level error. Error.isError (ES2026) checks for real errors across realms.
  • try/catch catches only errors thrown synchronously inside it, or awaited rejections inside an async function. It does not catch errors thrown later in a setTimeout callback or in a promise you didn't await.
  • finally runs after try or catch, even after return. A return inside finally overrides the earlier return or throw (avoid it).
  • catch { } without a binding is allowed. Rethrow errors you can't handle.
  • Safety nets: the window 'error' and 'unhandledrejection' events in browsers; process 'uncaughtException' and 'unhandledRejection' in Node (an unhandled rejection crashes Node by default since v15). React error boundaries don't catch errors in event handlers or async code.

The red pen

Common traps: mistake → fix

  • Mistake: try/catch catches errors from async callbacks

    Fix: not from timer callbacks or un-awaited promises.

  • Mistake: finally can't change the result

    Fix: a return inside finally replaces it.

  • Mistake: throw 'message' is fine

    Fix: you lose the stack trace and instanceof Error.

Easy to hard

Questions interviewers ask, easy to hard

  1. What error types exist? When do you get TypeError vs ReferenceError?
  2. How do you create a custom error class? Why set name?
  3. Does try/catch catch an error thrown inside setTimeout? Inside a promise?
  4. What happens if both try and finally return?
  5. Describe an error-handling strategy for a frontend app: boundaries, global handlers, logging, user messages and cause chains.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview