Error Handling

Error handling in JavaScript is essential to gracefully manage unexpected problems during code execution. It helps prevent your program from crashing and allows you to respond to errors effectively.

1. The try...catch Statement

The try...catch block lets you test a block of code for errors, and handle them if they occur:

  • try: Contains code that might throw an error.
  • catch: Runs if an error occurs inside try. Receives the error object.

📌 Deep Dive: Basic try...catch

JAVASCRIPT
try {
  JSON.parse("invalid json");
} catch (error) {
  console.log("Error caught:", error.message);
}
Output
Error caught: Unexpected token i in JSON at position 0

2. The finally Clause

The finally block always executes after try and catch, regardless of whether an error was thrown or caught. Useful for cleanup tasks.

📌 Deep Dive: Using finally

JAVASCRIPT
try {
  throw new Error("Oops!");
} catch (e) {
  console.log("Handling error:", e.message);
} finally {
  console.log("This always runs.");
}
Output
Handling error: Oops! This always runs.

3. Throwing Custom Errors

You can create and throw your own errors with throw. Useful for input validation or domain-specific error handling.

📌 Deep Dive: Throwing errors

JAVASCRIPT
function checkAge(age) {
  if (age < 18) {
    throw new Error("Underage: Access denied");
  }
  return "Access granted";
}

try {
  console.log(checkAge(15));
} catch (err) {
  console.log(err.message);
}
Output
Underage: Access denied
Illustration of error_handling
Illustration of error_handling

💡 Best Practice

Only use try...catch around code where you expect errors. Avoid catching errors silently without handling them, as it can hide bugs.

Error Handling Comparison
ApproachDescription
try...catchCatches and handles runtime errors.
throwManually triggers an error to be caught or propagate.
finallyRuns cleanup code regardless of errors.

⚠️ Avoid Overusing try...catch

Wrapping too much code in try...catch can degrade performance and obscure bugs. Use it selectively for risky operations.