When Things Go Wrong: Error Handling
Programs don't always run perfectly. A number might be missing, a name might be spelled wrong, or a website you ask for data might be down. Error handling means writing code that notices problems and deals with them calmly, instead of crashing.
What Is an Error?
An error is a JavaScript object that describes something that went wrong. When a problem happens, JavaScript throws the error, which means it stops the normal flow of the program. If nothing catches it, your script stops.
Every error has a message describing the problem, and a type. Two common types:
TypeError— you tried to do something with the wrong kind of value (for example, calling a method onnull).ReferenceError— you used a name JavaScript doesn't know.
console.log(userName); // ReferenceError: userName is not definedtry/catch: Catching Problems Safely
A try/catch statement lets you run risky code, and if it throws an error, run backup code instead. The word try means "attempt this," and catch means "if it fails, do this."
try {
const total = price * 2; // price doesn't exist!
console.log(total);
} catch (error) {
console.log("Something went wrong: " + error.message);
}
console.log("The program keeps going.");Output:
Something went wrong: price is not defined
The program keeps going.Without the try block, the error would have stopped the whole script. With it, the program continues. The error in the parentheses is a name you choose for the error object caught, so you can read its message.
throw: Making Your Own Errors
Sometimes you want to stop and report a problem yourself. Use the throw keyword with a new Error object:
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);
}finally: Always Runs
You can add a finally block after catch. It runs whether or not there was an error — good for cleanup like closing a loading indicator.
try {
console.log("Working...");
} catch (error) {
console.log("Oops: " + error.message);
} finally {
console.log("Always runs, error or not.");
}Why This Matters Later
In upcoming chapters on promises and fetching data from the internet, errors are common: networks fail, servers respond slowly. You'll see try/catch again, paired with async and await, to handle those failures gracefully.
callout tip Use error handling for expected problems (bad input, network failures), not as a fix for typos. Fix mistakes like misspelled variable names rather than catching them. callout
Exercise
What does JavaScript do when an error is thrown and no catch block exists?
Show answer
The script stops running at that point. The error propagates up and, in a browser, is shown in the console.
Exercise
Which error type would you expect from let x; x.toUpperCase();?
Show answer
A TypeError — x is undefined, and undefined has no toUpperCase method.
Spotted a mistake, or code that does not work?