🍓Try....catch

The try...catch statement in JavaScript allows you to handle errors that may occur in your code in a controlled way. It consists of a try block that contains the code that may throw an error, and a catch block that contains the code that will handle the error.

Here is an example of using try...catch to handle an error:

try {
  // code that may throw an error
  const result = someFunction();
  console.log(result);
} catch (error) {
  // code to handle the error
  console.error(error);
}

In this example, the try block contains a call to the someFunction() function, which may throw an error. If an error is thrown, execution of the try block will be stopped and control will be passed to the catch block. The catch block will receive the error object as an argument (in this case, it is stored in the error variable) and can use it to log the error or perform some other action.

If no error is thrown in the try block, the catch block will be skipped and execution will continue after the catch block.

You can also use the finally block to execute code after the try and catch blocks, regardless of whether an error was thrown or not. The finally block is optional and can be used like this:

try {
  // code that may throw an error
  const result = someFunction();
  console.log(result);
} catch (error) {
  // code to handle the error
  console.error(error);
} finally {
  // code that will always be executed
  console.log('This will always be executed');
}

In this example, the code in the finally block will always be executed after the try and catch blocks, whether an error was thrown or not.

The try...catch statement is useful for handling errors that may occur in your code and preventing them from crashing your program. It is especially useful when working with asynchronous code, where errors may be thrown in a callback function or in a Promise that is resolved or rejected.

Last updated