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.

Normally, when a JavaScript program encounters an error, be it syntactical or logical, it exits the program at that stage itself with a message indicating the cause of the error. Now, while this behaviour is acceptable during the development phase, it cannot continue once a program has been released to actual users. In these "live" situations, it is unprofessional to display cryptic error messages (which are usually incomprehensible to non-technical users); rather, it is more professional to intercept these errors and either resolve them (if resolution is possible), or notify the user with a clear error message (if not).

The term "exceptions" refers to those errors which can be tracked and controlled. For example, if a function attempts an unsupported operation on a built-in JavaScript object (say, trying to assign values to a non-existent array index), JavaScript will generate a "TypeError" exception, together with a message explaining the problem. Exceptions like these can be caught by the application, and appropriately diverted to an exception-handling routine.

In earlier versions of JavaScript, exception handling was almost non-existent - developers were stuck with the standard error construct provided by the browser, and had little or no control over what happened with the JavaScript interpreter encountered an error. With JavaScript 1.5, all of that changed - the language now supports standard "try-catch" exception-handling constructs, and provides a far greater degree of control over how errors are processed.

An example might make this clearer. Consider the following simple line of code,

<script language="JavaScript">

colours[2] = "red";

</script>

In the example above, JavaScript tries to change the value of the second element of the array variable "colours". Now, this variable does not exist in the variable namespace. What does JavaScript do? Rather than quietly packing up and moving to a new neighbourhood, JavaScript decides to generate an exception.
An error has occurred in the script on this page. Line: 8 Char: 1 Error: 'colours' is undefined Code: 0 URL: http://localhost/errors.html

You can see this from the first few lines of the output, which describe the exception, together with the variable that caused it.

From the above output, it's pretty clear what happened - an error occurred because the "colours" variable doesn't exist. And JavaScript also provides primitive debugging information on the error, such as the line on which the errant code resides. A little analysis of this debug data, and you'll quickly be able to identify the lines of code involved in the error.

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:

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

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".

Now, what you just saw was a very primitive exception handler, albeit one which isn't very useful on a production site. Ideally, you'd want the message generated by the exception handler to be a little more descriptive, and to contain some information on the source of the error.

JavaScript satisfies this requirement via two special, pre-defined properties of the Error object generated by an exception - the "name" and "message" properties. Take a look:

In this case, it doesn't matter what type of exception JavaScript generates
- the generic handler will catch it, ignore it and continue to process the rest of the script.

It should be noted, however, that this approach, although extremely simple, is *not* recommended for general use. It is poor programming practice to trap all errors, regardless of type, and ignore them; it is far better - and more professional - to anticipate the likely errors ahead of time, and use the "try-catch" construct to isolate and resolve them.

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:

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::

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:

alert(someArr[18])

* 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.

JavaScript also allows you to add a "finally" block to the "try-catch" block discussed previously. The "finally" block contains statements that are executed regardless of whether an exception is generated or not in the "try-catch" block.

If an exception is encountered when running the code within the "try" block, JavaScript will stop execution at that point, and look for a "catch" block to handle it. Once the error has been handled (or if no "catch" block exists), control passes to the "finally" block.

Here's the output:
The following error occurred: TypeError - 'a' is undefined Thank you for playing. Come back soon!

It's important to note that the code in the "finally" block will be executed even if errors are encountered in the corresponding "try" block.

Thus far, you've been working with JavaScript's built-in exceptions, which can handle most logical or syntactical errors. However, JavaScript also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises.

This is accomplished via JavaScript's "throw" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "throw" statement needs to be passed an error type. When the exception is raised, this exception name and description will be made available to the defined exception handler.

Let's go to a quick example. In the following piece of code, if the value entered into the form field is greater than 99, the code will manually generate a RangeError exception, which will be caught and displayed appropriately.

You can also create your own exceptions, via the JavaScript Error constructor. The following example demonstrates, by creating a custom error type called idiotUserError.

Error
Idiot user detected, terminating...

In this case, when you run the script, a new Error object will be created named idiotUserError, with the message specified in the Error object constructor. This error can now be thrown using the regular "throw" statement, as in the example above.

In this case, if the value entered into the form is blank or not "john", a custom exception will be thrown by the code. This custom exception can be caught by a generic exception handler such as the one used above, and the exception can be routed and resolved appropriately

And that just about covers it. In this article, I took you on a guided tour of exception handling in JavaScript, demonstrating how the "try" and "catch" blocks can be used to trap and resolve errors in script execution. I showed you how to retrieve the exception type and message, write exception handlers for different error types, and even generate your own custom errors. Finally, I wrapped things up with a real-world example that demonstrated how to build a simple form validator and generate exceptions suitable for processing by a generic "try-catch" handler.

In case you'd like to learn more about these topics, you should consider visiting the following links:

Note: Examples are illustrative only, and are not meant for a production environment. Code samples in this article have been tested on Microsoft Internet Explorer 6.0. Melonfire provides no warranties or support for the source code described in this article

sinaryuda

JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.

Some of the most common and beneficial uses of JavaScript involve timer functions. These functions are used to run client-side code at predefined intervals, thereby making it possible to add a new dimension - time – to your Web pages. By using JavaScript's timing functions, you can run a command after a specified delay has passed, loop events to run over and over again at predefined times, and synchronize multiple events on a timeline. JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.

Over the course of this article, I'll be exploring the various timing functions available in JavaScript, together with examples of how they can be used to create timed events in an HTML document. I'll introduce you to the setTimeout(), clearTimeout(), setInterval() and clearInterval() functions, and also show you how to use them to create a variety of different client-side applications, including a tickertape, a timed slideshow, and a countdown clock. So come on in! If you're new to JavaScript, you're going to find this article to be quite an eye-opener!

Let's start at the top, with the setTimeout() and clearTimeout() methods. These methods belong to the Window object, and are commonly used to run a particular piece of code after a pre-defined interval has passed. Consider the following example:

In this case, the setTimeout() method is used to run the function 5000 milliseconds (5 seconds). Thus, there are always two arguments to the setTimeout() method; the first is the code to run, and the second is the amount of time to wait before running it.

In this one, the window (which we'll assume has been popped open from some other parent window) closes automatically 30 seconds after it opens.

Just as you can set a timeout, you can also clear it with the clearTimeout() method. This method is used to remove a timeout previously declared with setTimeout(). Since there may be multiple calls to setTimeout() in the same document, it is mandatory to provide clearTimeout() with a reference so that it knows which timeout to clear. The following variant of the example above demonstrates:

In this case too, the window will never close, because the first timeout will be cancelled 10 seconds in by the call to clearTimeout() in the second.

Here's another example, this one containing two timers. The first one is set to close the window after 30 seconds. However, 10 seconds in, the second one will activate and ask the user to confirm the timeout. If the user does not confirm it, the timeout will be cancelled.

In this case, I'm using the setTimeout() method to call itself in a loop every second, and updating the value of the countdown clock on every iteration of the loop. When the countdown hits 0, an alert box is displayed.

Next up, the setInterval() and clearInterval() methods. The main difference between these methods and the ones on the previous page is this: the setTimeout() and clearTimeout() methods are used to run a particular piece of code once after a pre-defined interval has passed, while the setInterval() and clearInterval() methods are used to run a piece of code over and over again, with a pre-defined interval between successive runs.

In this case, the alert() box will keep appearing, once every 2 seconds. Thus, there are always two arguments to the setInterval() method – the first is the code to run, and the second is the amount of time between successive runs.

In this case, I've created the appearance of a moving tickertape by taking one character off the beginning of the message string and adding it to the end. Each time the tickerTape() function is called, the first character of the string is deleted and added to the end of the string, simulating a scrolling ticker-tape. The setInterval() function takes care of calling the tickerTape() function over and over again, once every 150 milliseconds. Finally, the "status" property is used to assign the result at each stage to the browser's status bar.

Just as you can set an interval, you can also clear it with the clearInterval() method. Here too, you must provide clearInterval() with a reference so that it knows which interval to clear. The following variant of the example above demonstrates:

In this case, when you click the button, the clearInterval() method will cancel the timer set earlier with setInterval() and the tickertape will stop moving.

Using a setInterval() function is identical to using a setTimeout() function in a loop. To illustrate this, consider the following example by rewriting the countdown clock example from a few pages back.

In this case, I've used the setInterval() method instead of the setTimeout() method to call the countDown() function over and over again. Note the difference between the version above and the one a few pages back - above, the call to setInterval() is outside the loop, whereas earlier, the call to setTimeout() was inside the loop.

Here's one more example, this one making a <div> appear when the mouse moves over a link and automatically hiding it again after 3 seconds:

Here, the images to be displayed are stored in a JavaScript array, and a "for" loop takes care of pulling out the correct image from the array and loading it into the page. The setInterval() method is used to refresh the image with a new one every 5 seconds.

You can also use the setInterval() method to move things around on a Web page, by incrementing an X- or Y-coordinate of a page element at a predefined interval. Consider the following example, which demonstrates by moving a <div> containing an image of a car across the screen.

Finally, I'll wrap things up with a more practical example, one which might come in handy in your Web development. In this next example, the task is to offer the user a file upload box, which he or she can use to upload files to a Web site. Once the user selects a file for upload and initiates the transfer, a dialog box should pop up with a message asking the user to be patient. Once the file upload completes, the dialog box (window) should automatically disappear.

Now, there are a number of ways to implement this. Here's how I'm going to do it:

1. Write the code to display a form for file upload, as well as the code to accept the file and transfer it to a data directory on the server. This will be implemented in PHP.

2. Add code to the script above to throw up a pop-up window once the upload begins.

3. Add code to the pop-up window to keep polling the parent window for file upload status. Once the upload has finished (signified by the parent browser window loading a new URL), the pop-up window will automatically close.

Once the upload is complete, the script above will redirect the browser to a success page (or an error page, if an error occurred).

Notice in the form that I'm opening a new window when the user clicks the submit button. This new window will show the "be patient" message, and must also keep checking the parent window at pre-defined intervals to see if the transfer is complete. Here's the code:

This script uses the setInterval() method to check the URL of the parent window every second and, when it detects that the parent has gone to the success or error page (indicating that the upload has completed), it automatically terminates itself with the self.close() method.

And that's about all I have time for. Over the course of this article, I introduced you to JavaScript's four timing functions, showing you how to use the setTimeout() and setInterval() methods to call a function once after a pre-defined delay, or repeatedly at a pre-defined interval. That was the easy part, and I followed it up with a bunch of examples designed to showcase some of the things you can do with this power. Among the example applications I built: a browser tickertape, a countdown clock, a timed slideshow, a variable-speed page object, and a polling status window.

I hope you had fun reading this article, and that the examples sparked off some ideas of where you can use these functions in your own scripts. 'Till next time, see ya!