Let
us pretend to be policeman. In the
last class ,
we "witness a crime". We get an Exception--java.lang.NumberFormatException. Look
at that error message, "thermometer.java:8" tells
us line 8 in thermometer.java is causing problem.
As a policeman, we should catch this bad guy.
How to analyze it? First, put that line (temperature=Double.parseDouble(args[0]);) into try
{}. Just like
try{temperature=Double.parseDouble(args[0]);}
Does try {} look
like a handcuff?
Just below try{...}, we need catch(NumberFormatException
nfe){...}. Right now, we just print out what that bad
guy say by using
catch(NumberFormatException nfe)
{System.out.println("Catch Exception"+nfe.getMessage());
System.exit(9);}
System.exit(9); means stop
running program. (Stop crime!, huh?).
The following is the whole code using try and catch.
class thermometer
{
public static void main(String[] args)
{
double temperature=0;
try{
temperature=Double.parseDouble(args[0]);
}
catch(NumberFormatException nfe)
{
System.out.println("Catch Exception="+nfe.getMessage ());
System.exit (9);
}
if(temperature>100.4)
System.out.println ("Beep Beep Beep");
else
System.out.println("No fever.");
}
}
Compile and run: java thermometer abc
You will see:
Catch Exception=For input string: "abc"
This tells us JAVA boy convert abc to
double. JAVA boy doesn't know how to do it so he gives you a wrong
message to remind you. |