Handling Bad Numbers
We now have a useful program to convert miles into Kilometers. However, the program has one fatal flaw. What happens if you enter an invalid number into it? What happens if you enter something such as “one1one”, or some other nonsense string. Try it and see.
If you enter a non-valid number your program will crash with a NumberFormatException.
You do not want your program to behave in this way. A properly designed program should never throw an exception and crash.
To keep from crashing as a result of a bad number, you must add an additional catch block to your program to handle the NumberFormatException. Listing 4.3 shows how to do this.
Listing 4.3: Handle Bad Numbers (BadNumbers.java)
import java.io.*;
public class BadNumbers
{
public static void main(String args[])
{
try
{
InputStreamReader inputStreamReader =
new InputStreamReader ( System.in );
BufferedReader in =
new BufferedReader ( inputStreamReader );
System.out.print("Enter a length in miles? ");
String miles = in.readLine();
double dMiles = Double.parseDouble(miles);
double dKilometers = 1.609344 *dMiles;
System.out.println("That is " + dKilometers +
" kilometers.");
}
catch(NumberFormatException e)
{
System.out.println(
"You entered an invalid number.");
}
catch(IOException e)
{
}
}
}The above program is nearly the same as the last example, except that four additional lines are added. These four lines will handle the exception, caused by an invalid number.
catch(NumberFormatException e)
{
System.out.println(
"You entered an invalid number.");
}
The above catch block will handle any exception of the type NumberFormatException. The parseDouble method will throw this type of exception if it is passed an invalid number. By adding this catch block, your program is able to display an error, rather than crashing.
Very Important! In this example, we already had a catch block. But we needed to add a new catch block for a new exception type. You can add as many catch blocks onto a try block as you need. Add one catch block for every type of exception that you need to handle.












