learn2kode.in

JavaScript Error Handling

What Is Error Handling in JavaScript?

JavaScript error handling is the process of detecting, managing, and responding to runtime errors so your application doesn’t crash or behave unexpectedly.
Instead of breaking the entire program, error handling allows you to gracefully handle mistakes and show meaningful messages to users or developers.

Types of Errors in JavaScript

1. Syntax Errors
Errors caused by incorrect JavaScript syntax.
2. Runtime Errors
Errors that occur while the program is running.
let x = y; // y is not defined
3. Logical Errors
Code runs but produces incorrect results.
The try...catch Statement
The try…catch block allows you to test code for errors and handle them safely.
Basic Syntax
try {
  // code that may throw an error
} catch (error) {
  // code to handle the error
}
Example
try {
  let result = JSON.parse("{name: 'John'}");
} catch (error) {
  console.log("Invalid JSON format");
}
This prevents the app from crashing when an error occurs.

Using finally Block

The finally block always executes, whether an error occurs or not.
try {
  console.log("Trying...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("This always runs");
}
Useful for cleanup tasks, such as closing files or stopping loaders.
Throwing Custom Errors in JavaScript
You can manually create errors using the throw keyword.
let age = 15;

if (age < 18) {
  throw new Error("Access denied: Age must be 18+");
}
Custom errors improve debugging and user experience.

Error Object Properties

JavaScript provides useful error details:
try {
  undefinedFunction();
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}
Common properties:

Handling Errors in Asynchronous JavaScript

Using try...catch with async/await
async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Failed to fetch data");
  }
}

Best Practices for JavaScript Error Handling

Common Mistakes to Avoid

Why Error Handling Is Important