Multiple catch Blocks
A single try statement can contain multiple conditional catch blocks, each of which handles a specific type of exception. In this case, the appropriate conditional catch block is entered only when the exception specified for that block is thrown. You can also include an optional catch-all catch block for all unspecified exceptions as the final catch block in the statement.
For example, the following function invokes three other functions (declared elsewhere), which validate its arguments. If a validation function determines that the component that it is checking is invalid, it returns 0, causing the caller to throw a particular exception.
Code:
function getCustInfo(name, id, email)
{
var n, i, e;
if (!validate_name(name))
throw "InvalidNameException"
else
n = name;
if (!validate_id(id))
throw "InvalidIdException"
else
i = id;
if (!validate_email(email))
throw "InvalidEmailException"
else
e = email;
cust = (n + " " + i + " " + e);
return (cust);
}
The conditional catch blocks route control to the appropriate exception handler.
Code:
try {
// function could throw three exceptions
getCustInfo("Lee", 1234, "lee@netscape.com")
}
catch (e if e == "InvalidNameException") {
// call handler for invalid names
bad_name_handler(e)
}
catch (e if e == "InvalidIdException") {
// call handler for invalid ids
bad_id_handler(e)
}
catch (e if e == "InvalidEmailException") {
// call handler for invalid email addresses
bad_email_handler(e)
}
catch (e){
// don't know what to do, but log it
logError(e)
}
Bookmarks