Sometimes you may need to have one or more conditional catch clauses to handle specific exceptions:
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
Guard for exceptions
JavaScript catch doesn't support any mechanism to filter errors. This limitation isn't too hard to get around: we can write a function guard():
function guard(e, predicate) {
if (!predicate(e)) throw e;
}
And then use it to e.g. only filter "not found" errors when downloading an image: