JavaScript Errors & Try...Catch
Errors happen when something goes wrong at runtime, like calling an undefined function or accessing a property of null. Unhandled errors stop script execution.
A `try...catch` block lets you handle errors gracefully: code in `try` runs normally, and if it throws, control jumps to `catch` instead of crashing the whole script.
try/catch/finally
`try { risky() } catch (err) { handle(err) } finally { cleanup() }` โ finally always runs, whether or not an error occurred.
Throwing custom errors
`throw new Error('message')` lets you signal your own error conditions, which can be caught by any surrounding try/catch.
try {
let result = JSON.parse("{invalid}");
} catch (err) {
console.log("Caught:", err.message.slice(0, 20));
}Caught: Unexpected tokenInvalid JSON throws, and catch handles it instead of crashing.
function check(age) {
if (age < 0) throw new Error("Age cannot be negative");
return age;
}
try {
check(-5);
} catch (e) {
console.log(e.message);
}Age cannot be negativeCustom errors can be thrown and caught just like built-in ones.
Key points
- try/catch handles runtime errors gracefully without crashing the script.
- finally runs regardless of whether an error occurred.
- throw new Error('msg') creates and raises a custom error.
- Errors have a `message` and `name` property for identifying the issue.
