Throwing different types of exceptions in JavaScript
Let's throw our own exception and see how the object with an error behaves in this case:
try {
throw new Error('an exception text');
} catch (error) {
console.log(error.name); // 'Error'
console.log(error.message); // 'an exception text'
}
As you can see, our exception type is
'Error'
. Any exceptions thrown
in this way will have the same type.
This, however, will not always be
convenient, since if we will have
several exceptions, we will not
be able to distinguish them from
each other.
JavaScript provides a solution to
this problem: you can throw exceptions
not only of the Error
type, but
also any built-in in JavaScript type of
error, for example, TypeError
,
SyntaxError
, RangeError
.
Let's throw an exception like
SyntaxError
as an example:
try {
throw new SyntaxError('an exception text');
} catch (error) {
console.log(error.name); // 'SyntaxError'
console.log(error.message); // 'an exception text'
}
Throw an exception of the
TypeError
type.
Throw an exception of the SyntaxError
and RangeError
types. Catch these
exceptions with a single try
-block. In
a catch
-block, output different error
messages for different exception types.