previous | index | next

Exception Handling and Command Line Arguments

The class below sums up integers from the command line and prints the total to standard output:
public class Adder {
    public static void main(String[] args) {
        int total = 0;
        for (String s : args) {
            total += Integer.parseInt(s);
        }
        System.out.println("The total is " + total);
    }
}
The program works given valid input:
49% java Adder 1 2 3 4 5
The total is 15 
But bad input causes the following behavior:
50% java Adder 1 2 3 foo 4 bar 5
Exception in thread "main" java.lang.NumberFormatException: For input string: "foo"...
Rewrite the class and, using only try and catch, handle the exception so that the following behavior is obtained:
57% java Adder 1 2 3 foo 4 bar 5
Ignoring bad input: foo
Ignoring bad input: bar
The total is 15
Do not use any if statements.

previous | index | next