The catch
block gets executed
for any error that is thrown
in the try
block.
In the example given above,
no matter what error occurs
withing the try
block,
we will get the output
"Something went wrong".
We can use instanceof
to
find what type of error
was thrown in the try
block
and
display a different output
for a specific type of error.
In the example above,
the JSON string being parsed is invalid
and
it throws a type of error - SyntaxError.
Inside the catch
block,
we use instanceof
to check
if the error
object
is an instance of SyntaxError
.
If the condition
error instanceof SyntaxError
is true,
we display "Invalid user input".
Otherwise, we throw the error.
In the example given above,
we use try...catch
to catch errors
that occur in the try
block.
However, we handle only a particular
instance of an error.
All unhandled errors are thrown again.
This is known as re-throwing an error.
The instanceof
operator is explained
in the instanceof
section
of the Learn JavaScript
course.