Java Reference
In-Depth Information
new value of
result
, is given in the text field. If the user clicks the
"Reset"
button,
then the running total, that is, the value of
result
, is set to zero. When the GUI is
first run, the running total, that is, the value of
result
, is set to zero.
Most of the details are similar to things you have already seen, but one new element
is the use of exception handling. If the user enters a number in an incorrect format,
such as placing a comma in a number, then one of the methods throws a
NumberFormatException
. If the user enters a number in an incorrect format, such as
2,000
with a comma instead of
2000
, the method
assumingCorrectNumberFormats
invokes the method
stringToDouble
with the alleged number string
"2,000"
as an argu-
ment. Then
stringToDouble
calls
Double.parseDouble
, but
Double.parseDouble
throws a
NumberFormatException
because no Java number string can contain a comma.
Since the invocation of
Double.parseDouble
takes place within an invocation of the
method
stringToDouble
,
stringToDouble
in turn throws a
NumberFormatException
.
The invocation of
stringToDouble
takes place inside the invocation of
assuming-
CorrectNumberFormats
, so
assumingCorrectNumberFormats
throws the
NumberFormat-
Exception
that it received from the invocation of
stringToDouble
. However, the
invocation of
assumingCorrectNumberFormats
is inside a
try
block. The exception is
caught in the following
catch
block. At that point, the
JTextField
(named
ioField
)
is set to the error message
"Error: Reenter Number."
.
Notice that if a
NumberFormatException
is thrown, the value of the instance vari-
able
result
is not changed. A
NumberFormatException
can be thrown by an invoca-
tion of
stringToDouble
in either of the following lines of code from the method
assumingCorrectNumberFormats:
result = result + stringToDouble(ioField.getText());
or
−
stringToDouble(ioField.getText());
result = result
If the exception is thrown, execution of the method
stringToDouble
ends immedi-
ately and control passes to the
catch
block. Thus, control passes to the
catch
block
before the previous addition or subtraction is performed. So
result
is unchanged, and
the user can reenter the last number and proceed with the GUI as if that incorrect
number were never entered.
Uncaught Exceptions
In a Swing program, throwing an uncaught exception does not end the GUI, but it may leave
it in an unpredictable state. It is best to always catch any exception that is thrown even if all
that the
catch
block does is output an instruction to redo something, such as reentering
some input, or just outputs an error message.