Java Reference
In-Depth Information
When execution transfers to the catch statement, the program performs a
validity check. Checking validity involves testing data to ensure that it uses the
correct data type. The code entered in the previous step handles an exception
caused by entering values that did not match the type of data the program
expected. You did not write the code to test for the condition yourself; you
merely caught the JVM interpreter's throw of the NumberFormatException.
Throwing an Exception
Input from the user also should be checked for reasonableness that is,
that the values entered are within reason as expected input. For example, in the
Commission program, any positive number might be a reasonable answer for
the sales amount, as you do not know how many sales a travel agent may have
completed to earn commission. Negative amounts and the number zero, while
valid integers, would not be reasonable. Additionally, according to the require-
ments document for the Commission program, a sales amount cannot be nega-
tive and cannot be zero. If users input a negative number or zero, a message
should display notifying them of their error.
Because you have already coded a catch statement to handle exceptions, you
can use a throw statement to create your own NumberFormatException when
the user inputs an unreasonable number. The throw statement, followed by the
constructor keyword, new, will transfer execution to the catch statement. Using
the catch statement to handle this exception, as well as for the previous excep-
tion, is an example of how Java allows the reuse of objects.
Line 38 in Figure 4-19 displays an if statement that tests for an unreasonable
sales amount that is less than or equal to zero. If the condition is found to be
true, the program will generate an exception through an explicit call to the
NumberFormatException() method. Because this section of code is within the
try statement, execution will transfer to the catch statement.
35
try
36
{
37
sales = Double .parseDouble ( answer ) ;
38
if ( sales <= 0 ) throw new NumberFormatException () ;
39
}
FIGURE 4-19
The following step enters code to throw an exception explicitly.
To Enter Code to Throw an Exception
1. Enter line 38 as shown in Figure 4-19.
TextPad displays the code to throw an exception in the TextPad coding
window (Figure 4-20).
Search WWH ::




Custom Search