Some errors are bugs that you need to fix. But some errors are things you can predict might go wrong, even in perfect code. A user might type something silly. A file might be missing. The internet connection might drop.
For these situations, JavaScript lets you catch errors, so your program can handle them gracefully instead of crashing. It looks like this:
const userInput = "{ this is not valid JSON }";
try {
const data = JSON.parse(userInput);
console.log("Got the data:", data);
} catch (error) {
console.log("😬 Oops! That wasn't valid JSON.");
console.log("Error type:", error.name);
}
console.log("The program keeps running!");
It prints
😬 Oops! That wasn't valid JSON. Error type: SyntaxError The program keeps running!
Here's how it works:
- JavaScript tries to run the code inside the
tryblock. - If everything goes well, the
catchblock is skipped completely. - If an error happens anywhere inside
try, JavaScript immediately jumps to thecatchblock. Theerrorvariable holds information about what went wrong, including itsname(the type) and itsmessage. - Either way, the program carries on after the
try...catch, instead of crashing.
A try...catch is like the safety net under a trapeze artist. The performer tries the trick. If they fall, the net catches them, and the show goes on. Without the net... well, the show definitely doesn't go on.
finally
You can add a finally block, which runs no matter what, whether there was an error or not. It's useful for cleaning up, like hiding a "Loading..." message:
function loadSettings(text) {
console.log("⏳ Loading...");
try {
const settings = JSON.parse(text);
console.log("✅ Loaded theme:", settings.theme);
} catch (error) {
console.log("❌ Couldn't load settings. Using defaults.");
} finally {
console.log("🏁 Done loading.");
}
}
loadSettings('{"theme": "dark"}');
loadSettings("garbage!!!");
It prints
⏳ Loading... ✅ Loaded theme: dark 🏁 Done loading. ⏳ Loading... ❌ Couldn't load settings. Using defaults. 🏁 Done loading.
It's tempting to wrap everything in try...catch so errors never show up. Don't! Especially, never write an empty catch block like catch (error) { }. That silently swallows the error, so the program carries on in a broken state and you have no idea why. That's not fixing a bug, that's hiding it under the carpet. Only catch errors that you expect and know how to handle.