JavaScript Exception Handling - Playing Catch (
Page 3 of 8 )
So that's what an error looks like. And now that you've seen what makes it
tick, how about writing something to handle it?
JavaScript allows you to trap errors using the standard "try-catch"
exception-handling combination. Here's what it looks like:
try {
execute this block
} catch (error) {
execute this block if error
}
Take a look at this rewrite of the previous example, which incorporates a simple
exception handler.
<script language="JavaScript">
try {
colours[2] = "red";
} catch (e) {
alert("Oops! Something bad just happened. Calling 911...");
}
</script>
And this time, when the script is executed, it will not generate an error -
instead, it will output
Oops! Something bad just happened. Calling 911...
This is a very basic example of how JavaScript exceptions can be trapped, and
appropriate action triggered. As you will see, the ability to handle errors
in a transparent manner throws open some pretty powerful possibilities...but
more on that later.
The first part of the code introduces you to the "try" block; this
instructs JavaScript to try - literally - to execute the statements within the
enclosing block.
try {
colours[2] = "red";
}
The "catch" block sets up the exception handler, in the event that
one is generated. This does the hard work of trapping the exception and suggesting
how to handle it
catch (e) {
alert("Oops! Something bad just happened. Calling 911...");
}
If an exception is generated, the "catch" segment of the code will
be triggered, and JavaScript's default error handling mechanism will be overridden
by the instructions in that code segment - in this case, displaying the text
"Something bad happened".