Learn JavaScript
Error Handling
36.6
Lesson

Rethrow Errors

The catch {...} block gets all the errors that occur in the try {...} block.

In the example given below, we create an error using the generateError() function. There is no error in the JSON data. Still, in the error message, it says JSON Error, making it difficult to debug.

We can avoid such situations using the rethrowing technique. It throws the errors that are not handled in the catch {...} block.

In the example given below, we use the instanceof operator to check the error type. Here, we are handling only the ReferenceError. The catch {...} block skips all the other errors that may occur in the code.

In the example given below, we are handling only the SyntaxError. The catch {...} block skips all the other errors that may occur in the code.