Java Reference
In-Depth Information
One professional created an online message board that relies on a small Java applet to enable
the transfer of data to and from the server without reloading the page (this was before Ajax). He
checked the code and everything was fine, and it continued to work fine after launching the board,
except that in about five percent of cases the Java applet initialized but then caused an error due
to the user being behind a particular type of firewall (a firewall is a means of stopping intruders
from getting into a local computer network, and many block Java applets because of Java's security
issues). It's impossible to determine whether a user is behind a certain type of firewall, so there is
nothing that can be done in that sort of exceptional circumstance. Or is there?
In fact, JavaScript includes something called the
try...catch
statement. This enables you to try to run
your code; if it fails, the error is caught by the
catch
clause and can be dealt with as you wish. For
the message board, this professional used a
try...catch
clause to catch the Java applet's failure and
redirected the user to a more basic page that still displayed messages, but without using the applet.
the try…catch statements
The
try...catch
statements work as a pair; you can't have one without the other. You use the
try
statement to define a block of code that you want to try to execute, and use the
catch
statement
to define a block of code that executes when an exception occurs in the
try
statement. The term
exception
is key here; it means a circumstance that is extraordinary and unpredictable. Compare that
with an
error
, which is something in the code that has been written incorrectly. If no exception occurs,
the code inside the
catch
statement never executes. The
catch
statement also enables you to get the
contents of the exception message that would have been shown to the user had you not caught it first.
Let's create a simple example of a
try...catch
clause:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 18: Example 1</title>
</head>
<body>
<script>
try {
alert("This is code inside the try clause");
alert("No Errors so catch code will not execute");
} catch (exception) {
alert("The error is " + exception.message);
}
</script>
</body>
</html>
Save this as
ch18 _ example1a.html
and open it in your browser.
This code defines the
try
statement, and as with all other blocks of code, you mark out the
try
block by enclosing it in curly braces.
Immediately following the
try
block is the
catch
statement, and notice that it includes
exception
inside a set of parentheses. This
exception
is simply a variable name, and it stores an object that