JavaScript provides mechanisms to handle errors gracefully in your code. Proper error handling can help you debug your code, provide meaningful messages to users, and prevent your application from crashing unexpectedly.

Types of Errors

  1. Syntax Errors:

    • Occur when there is a mistake in the code syntax.
    • Example:
      // Syntax Error: Missing closing parenthesis
    console.log("Hello, World!";
      
  2. Runtime Errors:

    • Occur during the execution of the code.
    • Example:
      // Runtime Error: undefined variable
    console.log(nonExistentVariable);
      
  3. Logical Errors:

    • Occur when the code doesn’t behave as expected due to a logic mistake.
    • Example:
      // Logical Error: Incorrect calculation
    let sum = 2 + 2;
    if (sum === 5) {
        console.log("Correct!");
    } else {
        console.log("Incorrect!"); // This will be logged
    }
      

Handling Errors with try...catch

The try...catch statement allows you to handle errors gracefully.

  try {
    // Code that may throw an error
    let result = 10 / 0;
    console.log(result);
} catch (error) {
    // Code to handle the error
    console.error("An error occurred:", error.message);
}

## Using `finally`
The `finally` block executes code after the `try` and `catch` blocks, regardless of whether an error was thrown or caught.

```javascript
try {
    let result = 10 / 0;
    console.log(result);
} catch (error) {
    console.error("An error occurred:", error.message);
} finally {
    console.log("This code runs no matter what.");
}
  

Throwing Custom Errors

You can throw custom errors using the throw statement.

  function divide(a, b) {
    if (b === 0) {
        throw new Error("Division by zero is not allowed");
    }
    return a / b;
}

try {
    let result = divide(10, 0);
    console.log(result);
} catch (error) {
    console.error("An error occurred:", error.message);
}
  

Error Objects

When an error occurs, an Error object is created with two main properties:

  • name: The type of error.
  • message: A description of the error.

You can also create custom error objects:

  class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = "CustomError";
    }
}

try {
    throw new CustomError("This is a custom error");
} catch (error) {
    console.error(error.name + ": " + error.message);
}
  

Common Error Types

JavaScript has several built-in error types that you can use to handle specific errors:

  • Error: Generic error object.
  • SyntaxError: Thrown when there is a syntax error.
  • ReferenceError: Thrown when an invalid reference is made.
  • TypeError: Thrown when a value is not of the expected type.
  • RangeError: Thrown when a value is outside the allowable range.
  • EvalError: Thrown when there is an error in the global eval() function.
  • URIError: Thrown when there is an error in encoding or decoding a URI.

Example:

  try {
    // ReferenceError: nonExistentFunction is not defined
    nonExistentFunction();
} catch (error) {
    if (error instanceof ReferenceError) {
        console.error("ReferenceError caught:", error.message);
    } else {
        console.error("An error occurred:", error.message);
    }
}