Things go wrong — bad input, failed network calls, missing data. Robust code anticipates failure and handles it gracefully instead of crashing. This chapter covers try/catch, throwing your own errors, and — just as important — debugging with the browser's developer tools.
try / catch / finally
try {const data = JSON.parse(input); // may throwprocess(data);} catch (error) {console.error("Bad input:", error.message);} finally {cleanup(); // always runs — success or failure}
Throwing errors
Raise your own errors with throw when something is invalid. Throw an Error object (not a string) so you get a message and a stack trace:
function enrol(age) {if (age < 16) {throw new Error("Must be at least 16 to enrol");}// …}try {enrol(14);} catch (e) {console.log(e.message); // "Must be at least 16 to enrol"}
Custom error types
Subclass Error to create meaningful error types you can catch specifically:
class ValidationError extends Error {constructor(message) {super(message);this.name = "ValidationError";}}try {throw new ValidationError("email is required");} catch (e) {if (e instanceof ValidationError) {// handle validation specifically}}
Async errors
With async/await, wrap awaits in try/catch. Remember (from Chapter 5) that fetch only rejects on network failure, so check response.ok yourself:
async function load() {try {const res = await fetch("/api/data");if (!res.ok) throw new Error(`HTTP ${res.status}`);return await res.json();} catch (e) {console.error("Load failed:", e.message);return null; // graceful fallback}}
Debugging with DevTools
console.logfor quick checks;console.tablefor arrays of objects;console.error/warnfor severity.- Set breakpoints in the Sources panel to pause execution and inspect variables step by step.
- Drop
debugger;into your code to pause there when DevTools is open. - Read the stack trace bottom-to-top to find where an error originated.
Practice
Write a safeParse(json) that returns the parsed object or null on failure using try/catch. Create a ValidationError class and a function that throws it. Then set a breakpoint and step through a small buggy function in DevTools.
Key takeaways
- 01Wrap risky code in try/catch; finally always runs for cleanup.
- 02throw new Error(msg) for invalid states — throw Error objects, not strings.
- 03Subclass Error for custom types you can catch with instanceof.
- 04For async, try/catch around awaits and check response.ok — fetch doesn't reject on 404/500.
- 05Debug with console methods, breakpoints and debugger; read stack traces bottom-to-top.
