Java Reference
In-Depth Information
contains information about any exception that may occur inside the
try
code block. We'll call
this object the
exception object
. Although the word
exception
is used here, you can use any valid
variable name. For example,
catch(ex)
would be fine.
The exception object contains several properties that provide information about the exception that
occurred, but the most commonly used properties are
name
and
message
. The aptly named
name
property contains the name of the error type, and the
message
property contains the error message
the user would normally see.
Back to the code at hand, within the
catch
block is the code that executes when an exception
occurs. In this case, the code within the
try
block will not throw an exception, and so the code
inside the
catch
block will never execute.
But let's insert a deliberate error. Change the highlighted line in the following code:
try {
alert("This is code inside the try clause");
ablert("No Errors so catch code will not execute");
} catch (exception) {
alert("The error is " + exception.message);
}
Save the document as
ch18 _ example1b.html
and open it in your browser.
The browser will start executing this code as normal. It will execute the first call to
alert()
inside
the
try
block and display the message to the user. However, the call to
ablert()
will cause an
exception. The browser will stop executing the
try
block, and instead will start executing the
catch
block. You'll see a message similar to "
The error is ablert is not defined
."
Let's change this code once again to introduce a different error. As before, modify the highlighted
line in the following code:
try {
alert("This is code inside the try clause");
alert('This code won't work');
} catch (exception) {
alert("The error is " + exception.message);
}
Save this as
ch18 _ example1c.html
and open it in your browser. You will not see any
alert
box
because this code contains a syntax error; the functions and methods are valid, but you have an
invalid character. The single quote in the word
won't
has ended the string value being passed to
alert()
.
Before executing any code, the JavaScript engine goes through all the code and checks for syntax
errors, or code that breaches JavaScript's rules. If the engine finds a syntax error, the browser deals
with it as usual; your
try
clause never runs and therefore cannot handle syntax errors.
throwing Errors
You can use the
throw
statement to create your own runtime exceptions. Why create a statement to
generate an exception, when a bit of bad coding will do the same?