Java Reference
In-Depth Information
As you'll see, all of these error messages are created using the try...catch and throw statements.
Because this example is all about try...catch and throw, you'll concentrate just on the
calcfactorial.htm page , in particular the butCalculate_onclick() function, which is con-
nected to the onclick event handler of the form's only button.
Start by looking at the try clause and the code inside it. The code consists of four if statements and
another line of code that puts the calculated factorial into the second text box. Each of the if statements
checks for a condition that, if true, would cause problems for your code.
The fi rst if statement checks that the calcFactorial() function, in the top frameset window, actually
exists. If not, it throws an error, which is caught by the catch block. If the user loads the calcfactorial
.htm page rather than the frameset page calcfactorialtopframe.htm, then without this throw
statement your code will fail.
try
{
if (window.top.calcFactorial == null)
throw “This page is not loaded within the correct frameset”;
The next three if statements check the validity of the data entered into the text box by the user. First
make sure the user entered something into the text box; then make sure the user entered a number, and
then fi nally check that the value is not negative. Again if any of the if conditions is true, you throw an
error, will be caught by the catch block. Each of the error messages you defi ne starts with an exclama-
tion mark, the purpose of which is to mark the error as a user input error, rather than an error such as
not being in a frameset.
if (document.form1.txtNum1.value == “”)
throw “!Please enter a value before you calculate its factorial”;
if (isNaN(document.form1.txtNum1.value))
throw “!Please enter a valid number”;
if (document.form1.txtNum1.value < 0)
throw “!Please enter a positive number”;
If everything is fi ne, the calcFactorial() function will be executed and the results text box will be
fi lled with the factorial of the number entered by the user.
document.form1.txtResult.value =
window.parent.calcFactorial(document.form1.txtNum1.value);
}
Finally, turn your attention to the catch part of the try...catch statement. First, any message thrown
by the try code will be caught by the exception variable.
catch(exception)
{
The type of data contained in exception will depend on how the error was thrown. If it was thrown
by the browser and not by your code, exception will be an object, the exception object. If it's thrown by
your code, then in this instance you've thrown only primitive strings. So the fi rst thing you need to do
is decide what type of data exception contains. If it's a string, you know it was thrown by your code
and can deal with it accordingly. If it's an object, and given that you know none of your code throws
Search WWH ::




Custom Search