Skip to main content

Command Palette

Search for a command to run...

Day 12: Error Handling in JavaScript

Managing Errors in JavaScript

Published
4 min read
Day 12: Error Handling in JavaScript

Welcome back to our JavaScript series!

Today, we’ll explore error handling in JavaScript—a crucial topic for creating robust and reliable applications. Proper error handling helps you manage and respond to runtime errors gracefully, improving the user experience and debugging process.

What is Error Handling?

Error handling refers to the process of responding to and managing errors that occur during the execution of your code. In JavaScript, errors can occur due to various reasons such as invalid operations, network issues, or unexpected user input.

Types of Errors in JavaScript

JavaScript has several built-in error types that you should be aware of:

  1. SyntaxError: Occurs when there is a mistake in the syntax of your code.

    • Example: Missing parentheses or brackets.
    // SyntaxError: Unexpected token
    console.log("Hello world";
  1. ReferenceError: Happens when trying to access a variable that hasn’t been declared.

    • Example: Using an undeclared variable.
    // ReferenceError: x is not defined
    console.log(x);
  1. TypeError: Raised when an operation is performed on a value of the wrong type.

    • Example: Calling a non-function as a function.
    let num = 10;
    // TypeError: num is not a function
    num();
  1. RangeError: Occurs when a value is not within a set or expected range.

    • Example: Invalid array length.
    // RangeError: Invalid array length
    let arr = new Array(-1);
  1. EvalError: Used for errors related to the eval() function. This is less common but still worth noting.

    • Example: Not often used in modern JavaScript.

Error Handling Techniques

JavaScript provides several mechanisms for handling errors:

1. Try...Catch Statement

The try...catch statement allows you to handle exceptions (errors) that occur in a block of code.

Syntax:

try {
    // Code that may throw an error
} catch (error) {
    // Code to execute if an error occurs
}

Example: Basic Try...Catch

try {
    let result = 10 / 0; // This will not throw an error, but just for illustration
    console.log(result);
} catch (error) {
    console.log("An error occurred:", error);
}

Example: Catching Specific Errors

try {
    let num = undefined;
    console.log(num.toFixed(2)); // Throws TypeError
} catch (error) {
    if (error instanceof TypeError) {
        console.log("TypeError caught:", error.message);
    } else {
        console.log("Other error caught:", error.message);
    }
}

2. Finally Block

The finally block, if present, will execute after the try and catch blocks, regardless of whether an error occurred or not.

Example: Using Finally

try {
    console.log("Trying to execute code");
    // Code that might throw an error
} catch (error) {
    console.log("Error occurred:", error.message);
} finally {
    console.log("This will always run");
}

3. Throwing Custom Errors

You can throw your own errors using the throw statement, which can be helpful for custom error handling.

Example: Throwing Custom Errors

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

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

4. Handling Errors in Asynchronous Code

For asynchronous code, such as promises and async/await, error handling is a bit different:

  • Promises: Use .catch() to handle errors.

Example: Handling Errors in Promises

function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulate async operation
        setTimeout(() => {
            reject(new Error("Failed to fetch data"));
        }, 1000);
    });
}

fetchData().then(data => {
    console.log("Data:", data);
}).catch(error => {
    console.log("Error:", error.message);
});
  • Async/Await: Use try...catch inside async functions to handle errors.

Example: Handling Errors with Async/Await

async function fetchData() {
    throw new Error("Failed to fetch data");
}

async function getData() {
    try {
        let data = await fetchData();
        console.log("Data:", data);
    } catch (error) {
        console.log("Error:", error.message);
    }
}

getData();

Best Practices for Error Handling

  1. Provide Meaningful Error Messages: Ensure your error messages are clear and informative to help with debugging.

  2. Use Specific Error Types: Catch specific errors (e.g., TypeError) rather than generic ones to handle different types of errors appropriately.

  3. Avoid Silent Failures: Always handle errors properly to avoid scenarios where errors are ignored, which can lead to unexpected behavior.

  4. Graceful Degradation: Ensure your application can handle errors gracefully and continue to function, if possible, rather than crashing.

Summary

Today, we covered error handling in JavaScript. We explored different types of errors, error handling techniques using try...catch, finally, and custom errors, and how to handle errors in asynchronous code. Proper error handling is essential for building reliable and maintainable applications. Tomorrow, we’ll dive into more advanced JavaScript topics.

More from this blog

Mohit's blog

51 posts