DEV Community

Cover image for Error Handling In Javascript
Shamsul huda
Shamsul huda

Posted on

Error Handling In Javascript

There are several ways to handle errors in JavaScript. Here are some common methods:

1. try...catch:

This is the most common way to handle errors in JavaScript. With this method, you wrap your code in a try block and catch any errors that may occur in a catch block.

try {
  // some code that might throw an error
} catch (error) {
  // handle the error
}
Enter fullscreen mode Exit fullscreen mode

2. throw:

You can use the throw keyword to manually throw an error in your code.
Example:

function divideByZero(num) {
  if (num === 0) {
    throw new Error('Cannot divide by zero');
  } else {
    return 10 / num;
  }
}

try {
  divideByZero(0);
} catch (error) {
  console.log(error.message);
}
Enter fullscreen mode Exit fullscreen mode

3. finally:

The finally block is executed regardless of whether an exception was thrown or caught. This block is often used to clean up resources or perform some action that needs to happen regardless of the outcome of the try...catch block.
Example:

try {
  // some code that might throw an error
} catch (error) {
  // handle the error
} finally {
  // do something whether an error was thrown or not
}
Enter fullscreen mode Exit fullscreen mode

4. Promise.catch():

If you're using Promises in your code, you can handle errors with the catch() method. This method catches any errors that occur in the Promise chain.
Example:

myPromise.then(result => {
  // do something with the result
}).catch(error => {
  // handle the error
});
Enter fullscreen mode Exit fullscreen mode

5. window.onerror:

This method is used to catch unhandled errors in your code. It can be helpful in debugging your code and finding errors that may have slipped through your other error handling methods.
Example:

window.onerror = function(message, url, line, column, error) {
  console.log('Error: ' + message + '\nURL: ' + url + '\nLine: ' + line + '\nColumn: ' + column + '\nStack trace: ' + error.stack);
}
Enter fullscreen mode Exit fullscreen mode

6. Error:

This method creates a new Error object with a specified message.
Example:

const err = new Error('Something went wrong.');
console.log(err.message);
Enter fullscreen mode Exit fullscreen mode

7. console.error():

This method logs an error message to the console.
Example:

console.error('Something went wrong.');
Enter fullscreen mode Exit fullscreen mode

Note that error handling is a crucial part of writing robust and reliable code. You should always make sure to handle errors properly in your code.

So, these are some of the most common ways to handle errors in JavaScript.

Top comments (0)