Library
LearnJavaScriptChapter 10
2 min read

Error Handling in Javascript

Error handling is a crucial part of any programming language, and JavaScript is no exception. Errors can happen at any time in your code due to incorrect input, unforeseen issues, or bugs. A well-structured error-handling strategy makes your application more robust and user-friendly.

This guide breaks down the essentials of handling errors in JavaScript, using examples to make concepts easy to understand.


Types of Errors in JavaScript#

JavaScript errors can broadly be classified into:

  1. Syntax Errors: Mistakes in code syntax.
    Example:

    javascript
    console.log("Hello World; // Missing closing quote
  2. Runtime Errors: Errors that occur while the program is running.
    Example:

    javascript
    console.log(nonExistentVariable); // Variable is not defined
  3. Logical Errors: Errors in the logic of the program.
    Example:

    javascript
    const total = 100 - 20 + 10; // Wrong logic for intended operation

Try-Catch Block#

The try-catch block is the foundation of error handling in JavaScript. It allows you to handle runtime errors gracefully.

Basic Syntax#

javascript
try {
    // Code that might throw an error
} catch (error) {
    // Code to handle the error
}

Example#

javascript
try {
    const result = 10 / 0;
    console.log(result);
    console.log(undefinedVariable); // Throws an error
} catch (error) {
    console.log("An error occurred:", error.message);
}

Throwing Custom Errors#

You can use the throw keyword to create custom errors in JavaScript.

Example#

javascript
function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }
    return a / b;
}
 
try {
    console.log(divide(10, 0));
} catch (error) {
    console.log(error.message);
}

Finally Block#

The finally block is executed regardless of whether an error occurred or not. It’s useful for cleanup operations.

Example#

javascript
try {
    console.log("Trying something risky...");
    throw new Error("Oops, something went wrong!");
} catch (error) {
    console.log("Caught an error:", error.message);
} finally {
    console.log("Finally block executed!");
}

Using try-catch with Async/Await#

Handling errors in asynchronous code can be tricky, but combining try-catch with async/await makes it more manageable.

Example#

javascript
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:", error.message);
    }
}
 
fetchData();

Handling Promises with .catch()#

For promises, the .catch() method captures errors.

Example#

javascript
fetch("https://api.example.com/data")
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.log("Error fetching data:", error.message));

Debugging Tips#

  1. Use Console Statements: console.log() or console.error() can help you debug issues.
  2. Enable Strict Mode: Use "use strict"; to catch common errors.
  3. Test Edge Cases: Always test your code with unexpected inputs.
  4. Error Logging: Use external services or log errors for future analysis.

Practice Code Snippet for You#

Live code runner

Error handling