Java Reference
In-Depth Information
Loading this revised code in a browser results in a normal browser error message telling you Expected ')'
instead of displaying the alert box in the catch block. This happens because this code contains a syn-
tax error; the functions and methods are valid, but you have an invalid character. The single quote in
the word won't has ended the string parameter being passed to the alert() method. At that point
JavaScript's syntax rules specify that a closing parenthesis should appear, which is not the case in this
code. Before executing any code, the browser's JavaScript engine goes through all the code and checks
for syntax errors, or code that breaches JavaScript's rules. If the engine fi nds a syntax error, the browser
deals with it as usual; your try clause never runs and therefore cannot handle syntax errors.
Throwing Errors
The throw statement can be used within a try block of code to create your own run-time errors. Why
create a statement to generate errors, when a bit of bad coding will do the same?
Throwing errors can be very useful for indicating problems such as invalid user input. Rather than using
lots of if...else statements, you can check the validity of user input, then use throw to stop code execu-
tion in its tracks and cause the error-catching code in the catch block of code to take over. In the catch
clause, you can determine whether the error is based on user input, in which case you can notify the user
what went wrong and how to correct it. Alternatively, if it's an unexpected error, you can handle it more
gracefully than with lots of JavaScript errors.
To use throw, type throw and include the error message after it.
throw “This is my error message”;
Remember that when you catch the exception object in the catch statement, you can get hold of the
error message that you have thrown. Although there's a string in this example throw statement, you
can actually throw any type of data, including numbers and objects.
Try It Out try … catch and Throwing Errors
In this example you'll be creating a simple factorial calculator. The important parts of this example are
the try...catch clause and the throw statements. It's a frameset page to enable you to demonstrate
that things can go wrong that you can't do anything about. In this case, the page relies on a function
defi ned within a frameset page, so if the page is loaded on its own, a problem will occur.
First let's create the page that will defi ne the frameset and that also contains an important function.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Frameset//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Example</title>
<script type=”text/javascript”>
function calcFactorial(factorialNumber)
{
var factorialResult = 1;
for (; factorialNumber > 0; factorialNumber--)
{
factorialResult = factorialResult * factorialNumber;
}
Search WWH ::




Custom Search