Error Handling — JavaScript interview guide
19 / 23Browser & Practical JSMedium priorityEasy 15 min
Error Handling
Use try/catch for code that can fail, throw Error objects (not strings), and catch async errors with .catch or try/catch around await.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
A thrown error unwinds the call stack until a catch
Execution phaseStep 1/12
script.js
1function a() { b(); }2function b() { c(); }3function c() {4throw new Error("Oops");5}6▶try {8a();9console.log("never runs");10} catch (err) {11console.log("caught:", err.message);12} finally {13console.log("cleanup");14}
Call Stack
last in, first outMemory / Scope
empty
Console
nothing printed yet
What happens:We enter the try block. If anything inside throws, JS will jump to catch.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Patterns
Custom error classes make errors easier to tell apart.
class ValidationError extends Error {
constructor(field) {
super(field + " is invalid");
this.name = "ValidationError";
}
}
window.addEventListener("unhandledrejection", (e) => {
reportToSentry(e.reason);
});Remember this
- try/catch cannot catch errors inside a setTimeout callback that runs later.
- finally always runs.
- Log unhandled rejections in production.
Interview questions
Why does try/catch around setTimeout not catch an error thrown inside the callback?
The callback runs later on a new call stack, after the try block has already finished.
Practice
- Wrap an async function so it returns [error, data] instead of throwing.
Keep learning
More in Browser & Practical JS