Exception Handling in JavaScript: Using Multiple Exception Handlers - Handling multiple errors: stepping back to the first example
(Page 2 of 5 )
As you probably remember, in the first article I showed a basic example that demonstrated how to handle two specific exceptions, which were thrown within a simple function. To quickly refresh the concepts, the respective function looked like this:
function loanCalculator(loanAmount,loanTerm){
if(!loanAmount||parseFloat(loanAmount)<10000||parseFloat
(loanAmount)>300000){
// throw exception
throw 'Loan amount must be between $10000 and $100000';
}
if(!loanTerm||parseInt(loanTerm)<1||parseInt(loanTerm)>30){
// throw exception
throw 'Loan term must be an integer positive value
between 1 and 30';
}
return parseFloat(loanAmount)/parseInt(loanTerm);
}
And, using the “try-catch” blocks, it could be called with the following lines:
try{
loanCalculator(10000,45);
}
// catch thrown exceptions
catch(e){
if(e=='Loan amount must be between $10000 and $100000'){
// do something to process this error
alert(e);
}
else if (e=='Loan term must be an integer positive value
between 1 and 30'){
// do something else to process this error
alert(e);
}
}
Even when the sample code has been shortened, it’s clear to see how two specific exceptions are trapped within the “catch” block. In particular, the function throws a custom exception whenever any of its arguments is considered invalid, by sending an error message as part of the exception itself.
The example shows a mechanism for trapping two different errors, which should be handled in different ways. Of course, the didactical sense of the above listed code resides on the support that JavaScript offers to handling multiple exceptions. Things get even more interesting by considering that the JavaScript 1.5 specification defines a set of six primary error types, which can be easily trapped through specific exception handlers.
Considering this propitious scenario, let’s have a look at the list of error types defined within the JavaScript 1.5 specification, along with some examples of how to catch them within an application.
Next: Working with primary error types: defining error types for the JavaScript 1.5 specification >>
More JavaScript Articles
More By Alejandro Gervasio