Why This Matters
Every program encounters errors — invalid input, missing files, network failures, division by zero. The difference between a program that crashes and one that handles problems gracefully is error handling. Learning to anticipate, catch, and recover from errors is essential for writing robust software.
Without error handling, a single unexpected value can crash your entire application. With it, you can show helpful messages, retry operations, or fall back to defaults.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
try/catch/finally: errors are caught and handled instead of crashing the program.
Code Example
// Basic try/catch
try {
const data = JSON.parse("not valid json");
} catch (error) {
console.log("Parse failed:", error.message);
}
// Output: Parse failed: Unexpected token ...
// Throwing your own errors
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws!
} catch (error) {
console.log("Caught:", error.message);
}
// Output: 5, then Caught: Cannot divide by zero
// finally always runs
try {
console.log("trying...");
throw new Error("oops");
} catch (e) {
console.log("caught:", e.message);
} finally {
console.log("cleanup done");
}
// trying... caught: oops cleanup done
// Error types
try {
null.property; // TypeError
} catch (e) {
console.log(e.constructor.name, e.message);
}Interactive Experiment
Try these exercises:
- Write a
safeParsefunction that wrapsJSON.parsein try/catch and returnsnullon failure. - Throw a custom error when a function receives a negative number.
- Use
finallyto always print "Done" after an operation, whether it succeeds or fails. - What happens if you throw inside a catch block? Can you nest try/catch?
- Try catching different error types: TypeError, RangeError, SyntaxError.
Quick Quiz
Coding Challenge
Write a function called `safeDivide` that takes two numbers and returns their division result. If the divisor is 0, it should return the string 'Error: Division by zero' instead of throwing. If either argument is not a number, return 'Error: Invalid input'.
Real-World Usage
Error handling is everywhere in production code:
- API requests: Network calls can fail.
try/catchwithfetchlets you show "retry" buttons instead of blank screens. - User input: Parsing dates, numbers, and JSON from user input always needs validation and error handling.
- File operations: Reading/writing files can fail (permissions, disk full, file not found).
- Database queries: Connections drop, queries timeout, constraints are violated.
- Third-party libraries: External code can throw unexpected errors that you need to catch at boundaries.