How to catch specific errors?

On this exercise’s example, e represents the thrown error.

try {
  throw Error('This error will get caught');
} catch (e) {
  console.log(e);
}
// Prints: This error will get caught
 
console.log('The thrown error that was caught in the try...catch statement!');
// Prints: 'The thrown error that was caught in the try...catch statement!'

How do I catch a specific error, say ReferenceError if I wanted to?

Check MDN documentation: try...catch - JavaScript | MDN

The pattern is if (e instanceof xxxError). Where xxxError is whichever specific error you’re trying to catch.

1 Like