catch error in javascript

In JavaScript, we can handle errors and exceptions using the try-catch statement. The try block contains the code that might throw an exception, while the catch block contains the code that handles the thrown exception.

Here's an example code snippet which demonstrates the usage of try-catch:

index.tsx
try {
  // code that might throw an exception
  const a = 10;
  const b = a.toUpperCase(); // this line will throw a TypeError
} catch (err) {
  // code that handles the exception
  console.log("Caught an exception: ", err);
}

// Output: Caught an exception: TypeError: a.toUpperCase is not a function
303 chars
11 lines

In the above example, the try block tries to convert a number to uppercase using the toUpperCase() method, which will throw an exception as this method is only defined for strings. The catch block receives the thrown exception object and logs it to the console.

We can also throw our own customized exceptions using the throw statement, as shown below:

index.tsx
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero"); // throw a customized exception
  }
  return a / b;
}

try {
  const result = divide(10, 0); // this line will throw an exception
  console.log(result);
} catch (err) {
  console.log("Caught an exception: ", err);
}

// Output: Caught an exception: Error: Cannot divide by zero
365 chars
16 lines

In the above example, the divide() function throws a customized exception if the second argument is zero. We then use try-catch to handle this exception and log it to the console.

gistlibby LogSnag