JavaScript ยท Chapter 48 of 55

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.

Example 1 (javascript)
try {
  let result = JSON.parse("{invalid}");
} catch (err) {
  console.log("Caught:", err.message.slice(0, 20));
}
Output
Caught: Unexpected token

Invalid JSON throws, and catch handles it instead of crashing.

Example 2 (javascript)
function check(age) {
  if (age < 0) throw new Error("Age cannot be negative");
  return age;
}
try {
  check(-5);
} catch (e) {
  console.log(e.message);
}
Output
Age cannot be negative

Custom 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.
๐Ÿ’ก Note: Only wrap code that can actually fail in try/catch โ€” overusing it can hide bugs instead of fixing them.

๐Ÿ“ Quick Quiz

1. Which block always runs, error or not?

2. How do you raise a custom error?

3. What happens to an unhandled error?