ptg7068951
Exceptions 253
9: }
10: }
11: System.out.println(“Those numbers add up to “+ sum);
12: }
13: }
After you save the application, run it with the command-line argument
1 3 5xand you see the output shown in Figure 18.2.
Listing 18.2 Continued
FIGURE 18.2
The output of the NewCalculator
application.
The try-catchblock in Lines 5–9 deals with NumberFormatException
errors thrown by Float.parseFloat(). These exceptions are caught within
the NewCalculatorclass, which displays an error message for any argu-
ment that is not a number. Because the exception is handled within the
class, the Java interpreter does not display an error. You can often deal
with problems related to user input and other unexpected data by using
try-catchblocks.
Catching Several Different Exceptions
A try-catchblock can be used to handle several different kinds of excep-
tions, even if they are thrown by different statements.
One way to handle multiple classes of exceptions is to devote a catch
block to each one, as in this code:
String textValue = “35”;
int value;
try {
value = Integer.parseInt(textValue);
catch (NumberFormatException exc) {
// code to handle exception
} catch (Arithmetic Exception exc) {
// code to handle exception
}