HTML and CSS Reference
In-Depth Information
Exception Handling
We will discuss approaches to implementing application wide exception handling later in
this topic. For now, it is worth emphasising that JavaScript does support “Java-style” excep-
tion handling, but without the benefits provided by static typing.
Any code can throw an exception without declaring that it will throw that exception. Any
data type can be thrown as an exception, although it is common practice to throw an object
with a code and a message. This function throws an exception if it is passed an even number:
> function dontLikeEven(num) {
if (num % 2 == 0) {
throw {code: 'even_number',
message: 'This function cannot be called with even numbers'
};
}
}
It is also possible to catch an exception, and provide logic to handle the failure scenario:
> function passNumber(num) {
try {
dontLikeEven(num);
} catch(e) {
console.log(e.code+':'+e.message);
console.log('Retying with ' + (num+1));
dontLikeEven(num+1);
}
}
In order to catch exceptions, a try block must be declared in the code. Only errors that occur
in this block will be caught. A catch block must be provided at the end of the try block, and
this will be passed any exception that occurs in the block.
The function above produces the following output if it is invoked with an even number:
> passNumber(2)
even_number:This function cannot be called with even numbers
Retying with 3
Search WWH ::




Custom Search