HTML and CSS Reference
In-Depth Information
Figure 7.21
An error was caught and its name and the reason for it are displayed.
The
throw
Statement.
The
throw
statement allows you to create your own condi-
tions for exceptions. Used within in the
try
block, a specific error condition can be tested
and thrown to the
catch
block. In the
catch
block you can create customized error mes-
sages to correspond to a particular error. See Example 7.13.
The
finally
Clause.
You can use the
finally
clause to execute statements after the
try
statement finishes, whether or not an exception occurred.
You can use the
finally
clause to make your script fail gracefully when an exception
occurs; for example, you might need to release a resource that your script has tied up.
The following example opens a file and then executes statements that use the file
(server-side JavaScript allows you to access files). If an exception is thrown while the file
is open, the
finally
clause closes the file before the script fails.
EXAMPLE
7.13
<html>
<head><title>Catch me if you Can!</title></head>
<body>
<script type="text/javascript">
1
var age=eval(prompt("Enter your age:",""));
2
try
{
3
if(age>120 || age < 0){
throw "Error1"
;
}
else if(age == ""){
4
throw "Error2
";
}
else if(isNaN(age)){
throw "Error3
";
}
}
5
catch(err)
{
6
if(err=="Error1")
{
alert("Error! The value is out of range");
}