JavaScript Lessons

JavaScript try catch: Stop Errors From Crashing Your Code

Use JavaScript try catch to catch errors before they crash your app. See clear examples of error handling and learn when to use finally.

Serhat ALPASLAN2 min read

what is a javascript class and how is it used?

try and catch blocks are used to handle potential errors that a piece of JavaScript code may produce. The try block contains a piece of code that may produce errors. If an error occurs in this piece of code, it passes the error to the catch block and runs the catch block’s handler. The catch block performs operations related to an error that occurs in the try block. Here, the catch block performs operations related to an error that occurs in the try block. For example, we can print the error message to the screen or create an error report.

The usage of the try and catch blocks is as follows:

 

try {
  // Code that may produce errors
} catch (error) {
  // Operations related to the error
}

In the following example, an attempt is made to access an element of an array in the try block. If the array does not have an element at that index, an error is passed to the catch block and the error message is printed to the screen:

try {
  const numbers = [1, 2, 3];
  console.log(numbers[4]); // Code that will cause an error
} catch (error) {
  console.log(error.message); // " numbers[4] is undefined"
}

 

Share it if it helped

Write a comment