How to handle errors in Javascript | Error handling in Javascript

Error handling is an important part of javascript programming. It allows you to handle unexpected situations and errors that may occur during the execution of your code.

Javascript image

Javascript provides different ways to handle errors :

  • Try...catch statement
  • Try...catch with finally block
  • Throw statement
  • Error Objects
  • Promises and catch()
Let's discuss one by one with example.

1. Try...catch statement :

This statement is used to catch and handle exceptions (errors) within a specific block of code. Consider following syntax/example for better understanding.

As per below syntax you have to write your code in try block and in catch block you can write logic to handle error. It always good option to use try..catch block in your code which prevents code execution smoother and prevents code breaks.
  try {
      // Your code that may throw an error
  } catch (error) {
      // Code to handle the error
  }

2. Try...catch with finally block :

The finally block is executed regardless of whether an error occurred or not. It's often used with try...catch block for cleanup operations.

Consider following syntax/example for better understanding. As per following syntax you have to write finally block after try..catch block. The finally block will be executed without fail after try..catch block.
  try {
    // Your code that may throw an error
  } catch (error) {
    // Code to handle the error
  } finally {
    // Code that always runs
  }

3. Throw statement :

Throw statement is used to manually throw custom exceptions or errors when certain conditions are met. Consider following syntax/example for better understanding.
  // Syntax
  throw new Error("This is a custom error message");

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

4. Error objects :

JavaScript provides built-in error objects like Error, SyntaxError, TypeError, etc., which is used to provide more specific information about errors.

Consider following syntax/example for better understanding. where we have used error object in catch block which provides extra specific information about actual error message.
 try {
    // Code that may throw a TypeError
    let x = undefinedVariable;
 } catch (error) {
      if (error instanceof ReferenceError) {
         console.error("ReferenceError:", error.message);
      } else {
          console.error("Other error:", error.message);
      }
 }

5. Promises and catch() :

While working with Promises, you can use the .catch() method to handle errors. Consider following syntax/example for better understanding. 

As per following example we are fetching some data and than using catch() method we are handling error after then block.
  fetchData()
    .then(data => {
        // Handle successful data retrieval
    })
    .catch(error => {
        // Handle error during data retrieval
    });
Thanks for reading this article, if you found this article useful then share it with your friends and share your thoughts in comment section.

Want to learn more about javascript? checkout these amazing  Javascript Tutorials .

Comments