Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

252 HOUR 18:Handling Errors in a Program


Output▼
Exception in thread “main” java.lang.NumberFormatException: For input
string: “5x” at sun.misc.FloatingDecimal.readJavaFormatString
(FloatingDecimal.java:1224)
at java.lang.Float.parseFloat(Float.java:422)
at Calculator.main(Calculator.java:5)

This message can be informative to a programmer, but it’s not something
you’d want a user to see. Java programs can take care of their own excep-
tions by using a try-catchblock statement, whichtakes the following form:
try {
// statements that might cause the exception
} catch(Exception e) {
// what to do when the exception occurs
}

Atry-catchblock must be used on any exception that you want a method
of a class to handle. The Exceptionobject that appears in the catchstate-
ment should be one of three things:

. The class of the exception that might occur
. More than one class of exception, separated by | characters
. A superclass of several different exceptions that might occur


The trysection of the try-catchblock contains the statement (or state-
ments) that might throw an exception. In the Calculatorapplication, the
call to the Float.parseFloat(String)method in Line 5 of Listing 18.1
throws a NumberFormatExceptionwhenever it is used with a string argu-
ment that can’t be converted to a floating-point value.
To improve the Calculatorapplication so that it never stops running with
this kind of error, you can use a try-catchblock.
Create a new empty Java file called NewCalculatorand enter the text of
Listing 18.2.

LISTING 18.2 The Full Text of NewCalculator.java
1: public classNewCalculator {
2: public static voidmain(String[] arguments) {
3: floatsum = 0;
4: for (int i = 0; i < arguments.length; i++) {
5: try {
6: sum = sum + Float.parseFloat(arguments[i]);
7: } catch(NumberFormatException e) {
8: System.out.println(arguments[i] + “ is not a
➥number.”);
Free download pdf