Exception Handling (try/catch)
When something goes wrong — parsing invalid JSON, calling a method that doesn't exist — JavaScript throws an error. Left uncaught, that crashes your program. try/catch lets you catch it and decide what happens instead.
try {
const result = JSON.parse("not valid json");
} catch (error) {
console.log("Could not parse JSON!");
}Could not parse JSON!
JavaScript tries to run the code inside try. The moment JSON.parse() throws, it jumps straight to the catch block instead of crashing — the program keeps running normally after that.
Accessing the actual error, and finally
catch (error) lets you access the actual error object — useful for logging or showing a real message instead of a generic one. finally runs no matter what happened — whether an error was thrown or not — which makes it the right place for cleanup code.
try {
const result = JSON.parse("not valid json");
} catch (error) {
console.log(`Error: ${error.message}`);
} finally {
console.log("This always runs");
}Error: Unexpected token o in JSON at position 1 This always runs
That error message came from the real JavaScript engine, not something written to look plausible — this is genuinely what you'll see if you run this exact code.
Next: classes — bundling data and the functions that work on it together.
Practice exercise
Try parsing the string "abc" as JSON with JSON.parse(), catch the error, and print "Not valid JSON" instead of crashing.