How to use Try/Catch in JavaScript?

The try/catch statement is used in JavaScript to handle exceptions (run-time errors) in your code.

Here’s the general syntax for using try/catch in JavaScript:

try {
  // code to try
} catch (error) {
  // code to handle exceptions (errors)
}

Here’s a simple example to show how try/catch works in JavaScript:

try {
  // code to try
  let x = y + 1;
} catch (error) {
  // code to handle exceptions (errors)
  console.error(error.message);
}

In this example, the code inside the try block tries to assign the value of y + 1 to x. Since y is undefined, this will result in a ReferenceError. The error is caught by the catch block and its message is logged to the console using console.error().