Exception Handling in JavaScript with Examples

Exception Handling in JavaScript with Examples

JavaScript is a powerful language, but like any programming language, it encounters errors. Proper exception handling ensures smooth execution and helps debug issues effectively. In this blog, we will explore different ways to handle exceptions in JavaScript with examples.

Understanding JavaScript Errors

JavaScript errors can be classified into three main types:

  1. Syntax Errors – Occur when there is an issue in the code syntax.

  2. Runtime Errors – Occur during execution, such as calling an undefined function.

  3. Logical Errors – Happen due to incorrect logic but do not throw explicit errors.

The try...catch Statement

The try...catch statement is the most common way to handle exceptions in JavaScript.

Syntax:

try {
    // Code that may throw an error
} catch (error) {
    // Handle the error
} finally {
    // Code that runs regardless of an error
}

Example:

try {
    let result = 10 / 0;  // Division by zero (infinity, not an error in JS)
    console.log(result);
    let x = y;  // ReferenceError: y is not defined
} catch (error) {
    console.error("An error occurred:", error.message);
} finally {
    console.log("Execution completed.");
}

Throwing Custom Errors

You can create and throw custom errors using the throw statement.

Example:

function validateAge(age) {
    if (age < 18) {
        throw new Error("Age must be 18 or above.");
    }
    return "Access granted";
}

try {
    console.log(validateAge(16));
} catch (error) {
    console.error("Validation Error:", error.message);
}

Using finally

The finally block always executes, whether an exception occurs or not.

Example:

try {
    console.log("Trying to execute code...");
    throw new Error("An unexpected error");
} catch (error) {
    console.error("Caught an error:", error.message);
} finally {
    console.log("This will always execute.");
}

Best Practices for Exception Handling

  • Use try...catch for handling predictable errors.

  • Avoid catching and ignoring errors without logging them.

  • Use meaningful error messages for debugging.

  • Prefer specific error handling instead of catching all exceptions.

  • Always clean up resources in the finally block if needed.

Conclusion

Exception handling in JavaScript is crucial for writing robust and error-free applications. By using try...catch, finally, and custom error handling techniques, you can improve the stability of your code. Implement these practices in your JavaScript projects to handle errors efficiently.