Next: Multiple catch blocks. Up: More on exceptions. Previous: Checked and unchecked exceptions.


String parsing exceptions

The Integer.parseInt() and Double.parseDouble() class methods both take a String parameter and converts it into a number. But what if the string doesn't look like a number? Then it throws an exception (a NumberFormatException, in this case).

try {
    IO.print("Type a number: ");
    String str = IO.readLine();
    int i = Integer.parseInt(str);
    IO.println(2 * i);
} catch(NumberFormatException e) {
    IO.println("That's not a number.");
}
Integer.parseInt() will raise a NumberFormatException if the line contains any characters that don't belong in a number. This provides a more robust technique for checking the user's input. So the user might experience the following.
Type a number: 3 2
That's not a number.
On the other hand, if there wasn't a problem with what the user types, it would simply proceed normally.
Type a number: 45
90


Next: Multiple catch blocks. Up: More on exceptions. Previous: Checked and unchecked exceptions.