Main Page

Errors versus Exceptions

some other reason, perhaps, that the array has no items in it? There is no way to know why the invalid
value was returned. Errors and error handling help eliminate this conundrum.
With the incorporation of error handling into JavaScript, Web developers now have the ability to better
control code. Good error-handling techniques allow smooth developing, debugging, and deploying of
scripts. In many ways, such techniques are actually more important in JavaScript than other program-
ming languages because it lacks a standard development environment, such as Visual Studio.NET for
the .NET Framework or NetBeans for Java development, to guide developers.
Errors versus Exceptions
When talking about errors in programming, you really have only two categories of primary concern:
syntax errors and runtime errors.
Syntax errors, also called parsing errors, occur at compile time for traditional programming languages
and at interpret time for JavaScript. These errors are a direct result of an unexpected character in the
code and thus prevent it from being fully compiled/interpreted. For example, the following line causes
a syntax error because it is missing a closing parenthesis:
When a syntax error occurs, the code cannot be executed. In JavaScript, only the code contained within
the same thread as the syntax error is affected. Code in other threads and other externally referenced
files still execute appropriately assuming nothing in them depends on the code containing the error.
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). In this
case, the problems are not with the syntax of the code. Rather, an operation attempting to complete is
illegal in some way. Example:
In the previous code, an attempt is made to access a method of the
object named
. Syntactically this line is correct, however, no such method exists. This
causes the browser to return an exception.
Exceptions only affect the thread in which they occur, allowing other JavaScript threads to continue nor-
mal execution. Consider the following HTML page:
<title>Exception Test</title>
<script type=”text/javascript”>
function handleLoad() {
function handleClick() {
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 412

JavaScript EditorFree JavaScript Editor     Ajax Editor