Error Handling

Error handling is a crucial aspect of programming that ensures your application can gracefully handle unexpected situations, providing a better user experience and easier debugging. JavaScript provides several mechanisms to handle errors effectively.

1. The TRY … CATCH Statement

The try...catch statement is used to handle exceptions (runtime errors). The code inside the try block is executed, and if an error occurs, the control is transferred to the catch block.

Syntax:

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

Example:

try {
  let result = 10 / 0;
  console.log(result); // Infinity
  let data = JSON.parse('{"name": "John"'); // Missing closing brace
} catch (error) {
  console.log("An error occurred: " + error.message);
}

In this example, the JSON.parse method throws a syntax error because of the malformed JSON string. The catch block catches the error and logs an error message to the console.

2. The FINALLY Block

The finally block is optional and contains code that will always be executed, regardless of whether an error was thrown or not. This is useful for cleaning up resources or performing other necessary actions.

Syntax:

try {
  // Code that may throw an error
} catch (error) {
  // Code to handle the error
} finally {
  // Code to be executed regardless of an error
}

Example:

try {
  let data = JSON.parse('{"name": "John"');
} catch (error) {
  console.log("An error occurred: " + error.message);
} finally {
  console.log("This will always be executed");
}

In this example, the finally block is executed after the catch block, regardless of whether an error occurred.

3. Throwing Custom Errors

You can throw custom errors using the throw statement. This is useful for creating more specific and meaningful error messages.

Syntax:

throw new Error("Something went wrong");

Example:

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);
}

In this example, the divide function throws a custom error if the second argument is zero. The catch block catches the error and logs an appropriate message.

4. Error Object Properties

The error object in JavaScript provides several useful properties that can help you understand and handle errors better.

  • name: The name of the error (e.g., ReferenceError, TypeError).

  • message: A human-readable description of the error.

  • stack: A stack trace that can help you debug the error.

Example:

try {
  undefinedFunction();
} catch (error) {
  console.log("Error name: " + error.name);
  console.log("Error message: " + error.message);
  console.log("Stack trace: " + error.stack);
}

In this example, the catch block logs the error's name, message, and stack trace to the console.

5. Handling Different Types of Errors

JavaScript has several built-in error types that you can handle specifically, such as SyntaxError, ReferenceError, TypeError, and more.

Example:

try {
  eval("var a = ;"); // SyntaxError
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log("Syntax Error: " + error.message);
  } else {
    console.log("Other Error: " + error.message);
  }
}

In this example, the catch block checks the type of the error and handles it accordingly.

Use Case:

Suppose you're building a simple web application that processes user input and you want to handle potential errors gracefully.

Example:

function processUserInput(input) {
  try {
    if (input.trim() === "") {
      throw new Error("Input cannot be empty");
    }
    let number = parseInt(input);
    if (isNaN(number)) {
      throw new Error("Input must be a number");
    }
    console.log("Processed number: " + number);
  } catch (error) {
    console.log("Error: " + error.message);
  } finally {
    console.log("Processing complete");
  }
}

let userInput = prompt("Enter a number:");
processUserInput(userInput);

In this example:

  • The processUserInput function takes user input and processes it.

  • It checks if the input is empty and throws an error if it is.

  • It attempts to convert the input to a number and throws an error if the conversion fails.

  • The catch block handles any errors that occur, and the finally block logs a completion message.

This use case demonstrates how error handling can improve the robustness of your application by managing unexpected situations and providing meaningful feedback to users. Understanding error handling is essential for writing reliable and maintainable JavaScript code. As you progress, you'll encounter more complex error handling scenarios, such as dealing with asynchronous errors and custom error classes, which will further enhance your ability to manage errors effectively.


Help us improve the content 🤩

You can leave comments here.

Last updated