Home arrow JavaScript arrow Page 5 - JavaScript Exception Handling

All For One... - JavaScript

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.

  1. JavaScript Exception Handling
  2. Anatomy Of An Exception
  3. Playing Catch
  4. Being Verbose
  5. All For One...
  6. The Final Solution
  7. Raising The Bar
  8. Endzone
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 239
August 14, 2003

print this article



You can also write specific exception handlers for different types of exceptions, by using an "if" test to check the exception type within the "catch" block. Consider the following handler, which only handles TypeError exceptions:

<script language="JavaScript">

try {
colours[2] = "red";
} catch (e) {
if (e instanceof TypeError)
alert("Bad or undefined variable!");


Here's the output:

Bad or undefined variable!

Of course, this handler will now only restrict its activities to TypeError exceptions. All other errors will be ignored.

The JavaScript 1.5 specification defines six primary error types, as follows:

EvalError - raised when the eval() functions is used in an incorrect manner;

RangeError - raised when a numeric variable exceeds its allowed range;

ReferenceError - raised when an invalid reference is used;

SyntaxError - raised when a syntax error occurs while parsing JavaScript code;

TypeError - raised when the type of a variable is not as expected;

URIError - raised when the encodeURI() or decodeURI() functions are used in an incorrect manner;

You can trap more than one exception, and handle each one in a different way, by using multiple "if" constructs within a single "catch" block.

try {
execute this block
} catch (error) {
if (error instanceOf errorType1)
do this
else if (error instanceOf errorType2)
do this
... and so on ...
do this if none of the error types above match

If an exception is encountered while running the code within the "try" block, the JavaScript interpreter stops execution of the block at that point and begins checking each "if" test within the "catch" block to see if there is a handler for the exception. If a handler is found, the code within the appropriate "if" block is executed; if not, control moves to the "else" block, if one exists.

Once the "try" block has been fully executed and assuming that the program has not been terminated, the lines following the "try" block are executed.

Take a look at the next example, which demonstrates how this works by revising the example on the previous page::

<script language="JavaScript">

// ask for user input
code = prompt("Enter some JavaScript code");

// run the code and catch errors if any generated
try {
} catch (e) {
if (e instanceof TypeError)
alert("Variable type problem, check your variable definitions!")
else if (e instanceof RangeError)
alert("Number out of range!")
else if (e instanceof SyntaxError)
alert("Syntax error in code!");
alert("An unspecified error occurred!");


You can test this exception handler by entering different lines of code into the box that appears when you load the page into your browser.

* To generate a TypeError, try accessing a non-existent array subscript, like this:


* To generate a RangeError, try creating an array with an extremely large size, like this:

var someArr = new Array(89723742304323248456)

* To generate a SyntaxError, try entering a line of code with a deliberate error in it, like this:

vara count = 99

As you will, in each case, the exception handler above will identify the error type and display an appropriate alert message. The "else" block works as a catch-all exception handler, processing all errors which have not been accounted for in the preceding "if" clauses.

>>> More JavaScript Articles          >>> More By icarus, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Javascript for Beginners: An Introduction
- Introduction to JavaScript
- Adding Elements to a Tree with TreeView jQue...
- Using the Persist Argument in a TreeView jQu...
- Using Unique and Toggle in a TreeView jQuery...
- Using Event Delegation for Mouseover Events ...
- Using the Animate Option in a Treeview jQuer...
- Using HTML Lists with Event Delegation in Ja...
- Opened and Closed Branches on a TreeView jQu...
- Mouseover Events and Event Delegation in Jav...
- Creating a TreeView JQuery Hierarchical Navi...
- Event Delegation in JavaScript
- A Look at the New YUI Carousel Control
- Working with Draggable Elements and Transpar...
- Displaying Pinned Handles with Resizable Con...

Developer Shed Affiliates


Dev Shed Tutorial Topics: