JavaScript Exception Handling (
Page 1 of 8 )
Wondering why JavaScript doesn't include exception-handling constructs like its bigger cousins? Well, the newest version of JavaScript does - and this article tells you all about it, explaining how you can use the new Error object and the "try-catch" constructs to trap and resolve errors in script execution.It's sad but true - error-free code is still largely a Utopian dream. No matter
how careful you are, no matter how deep your knowledge or how good your IDE,
you're bound to slip up sooner or later. And when you do, and your routines
decide to go AWOL, you need to take remedial action.
Most programming languages come with built-in exception handling capabilities.
These exception handlers make it possible to catch errors and resolve them sensibly,
thereby insulating the user from complex decisions and incomprehensible technical
information. As a professional developer, you should always wrap your code in
exception handling routines, if only to avoid embarrassing flameouts in front
of your customers.
Up until recently, JavaScript was *not* one of the languages with sophisticated
exception handling. Most of the time, developers were stuck with the built-in
JavaScript debugger to track errors in their scripts, and had to unhappily consent
to the browser taking care of errors for them in the most direct way possible
- an ugly pop-up in the user's face. All that has changed, though, with the
arrival of JavaScript 1.5 (available from Internet Explorer 6.0 and Netscape
6.0), which finally allows developers to wrap their code in "try-catch"
exception handlers and discreetly resolve errors internally, at the application
layer itself.
That's where this article comes in. Over the next few pages, I'm going to be
looking at exception handling, with a special focus on exceptions in the JavaScript
universe. I'll be explaining the most common error types you'll encounter, together
with the JavaScript constructs you can use to catch and resolve them, and I'll
include lots of examples so that you can see how it works in practice. So come
on in, and let's get started.