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.
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: 8Char: 1Error: 'colours' is undefinedCode: 0URL: 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.