Can you write this from memory?
Wrap code in a `try...catch` block.
In JavaScript, sync errors throw. Async errors reject. Unhandled rejections crash your process. Throwing a string instead of an Error object loses the stack trace. Catching too broadly hides bugs.
JavaScript error handling has more moving parts than most languages. We cover each pattern so you handle errors consistently without thinking about it.
When to Use JavaScript Error Handling
- Wrap code that may throw (JSON.parse, DOM access, network calls).
- Translate low-level errors into domain-specific messages.
- Handle async failures with try/catch around await.
Check Your Understanding: JavaScript Error Handling
Handle an async fetch error and return a fallback value.
Wrap await fetch in try/catch and return a safe default; explain how to surface the error for observability.
What You'll Practice: JavaScript Error Handling
Common JavaScript Error Handling Pitfalls
- Swallowing errors without logging
- Forgetting to handle Promise rejections
- Not using try/catch with await
- Throwing non-Error objects
JavaScript Error Handling FAQ
Should I throw strings or Error objects?
Throw Error objects so you get stack traces and consistent error handling.
How do I handle promise rejections?
Use try/catch with await or attach .catch to the promise chain; avoid unhandled rejections.
JavaScript Error Handling Syntax Quick Reference
try {
riskyOperation();
} catch (error) {
console.error(error.message);
} finally {
cleanup();
}try {
const data = await fetchData();
} catch (error) {
handleError(error);
}class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}JavaScript Error Handling Sample Exercises
What does this code output?
DoneWhat does this code output?
In a catch block `(e)`, handle only `TypeError` using `instanceof`, else re-throw.
if (e instanceof TypeError) {
} else {
throw e;
}
+ 12 more exercises