HTML and CSS Reference
In-Depth Information
EXAMPLE
7.13 (
CONTINUED
)
if(err=="Error2"){
alert("Error! You didn't enter your age");
}
if(err=="Error3"){
alert("Error! The value is not a number");
}
}
7
if (age < 13){
alert("You pay child's fare!");
}
else if(age < 55 ){
alert("You pay adult fare.");
}
else { alert("You pay senior fare.");
}
</script>
</body>
</html>
EXPLANATION
1
This simple example is here to show you how the
try/catch/throw
statements can
be used for handling errors. For something like this, you will probably find it eas-
ier to test the program in the
if
conditionals, but we'll use it to demonstrate how
to throw exceptions. First, the user is prompted for his or her age.
2
The
try
block is entered to test for the possible error conditions defined by the
programmer.
3
If an invalid age is entered (i.e., an age less than 0 or greater than 120). An error
string, “Error1” is thrown and picked up in the
catch
block to be tested.
4
If the user didn't enter anything, the string “Error2” is thrown and picked up in
the
catch
block.
5
In the
catch
block, the errors will be handled based on the error string that was
thrown from the
try
block.
6
The
err
value being passed to the catch block is one of the values that was thrown
from the
try
block; for example, “Error1”, “Error2”, “Error3”.
7
Because all the testing and error handling was handled in the
try/catch
blocks, the
rest of the program can continue with no further testing of the age variable (see
Figure 7.22).