Java Reference
In-Depth Information
of cases the Java applet initialized but then caused an error due to the user being behind a particular
type of fi rewall (a fi rewall is a means of stopping hackers from getting into a local computer network).
There is no way of determining whether a user is behind a certain type of fi rewall, 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, Paul 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 state-
ment to defi ne a block of code that you want to try to execute, and use the catch statement to defi ne
a block of code that will execute if an exception to the normal running of the code occurs in the block
of code defi ned by 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 is never executed.
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 fi rst.
Let's create a simple example of a try...catch clause.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Try/Catch</title>
</head>
<body>
<script type=”text/javascript”>
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 trycatch.htm.
This code fi rst defi nes the try statement; as with all other blocks of code, you mark out the try block by
enclosing it in curly braces.
Search WWH ::




Custom Search