try catch throw in javascript

In JavaScript, try-catch is used for exception handling. The try block contains the code that may throw an exception, and the catch block contains the code that handles the exception.

index.tsx
try {
  // code that may throw an exception
} catch (error) {
  // code that handles the exception
}
101 chars
6 lines

Here's an example:

index.tsx
try {
  let x = y; // variable y is not defined
} catch (error) {
  console.log('An error occurred: ' + error.message); // An error occurred: y is not defined
}
161 chars
6 lines

You can also manually throw an exception using the throw keyword, which can be caught by a try-catch block:

index.tsx
try {
  let x = 10;
  if (x > 5) {
    throw new Error('x must be less than or equal to 5'); // manually throw an exception
  }
} catch (error) {
  console.log('An error occurred: ' + error.message); // An error occurred: x must be less than or equal to 5
}
258 chars
9 lines

gistlibby LogSnag