Sei sulla pagina 1di 1

114-15.

Example of try-catch blocks to handle NumberFormatException.


public static void main(String[] args)
{ String[] in1={"Hello","23","42"};
String[] in2={"Tar Heel", "Strongbad", "1234"};
int count=-1; // Iteration counter.
String s="";
int num1, num2; // Will hold integer version of String.
while (true)
{
count++;
System.out.println("Iteration "+ count +": input is "+ in1[count] +
" and "+ in2[count]);
try
{ s=in1[count];
num1=Integer.parseInt(s);
s=in2[count];
num2=Integer.parseInt(s);

// If we get to this point, we have successfully read 2 integers.


// Display the numbers and leave the loop.
System.out.println("Numbers are "+num1+" and "+num2+".");
break;
} // End of try block
catch (NumberFormatException e)
{ System.out.print("Sorry, \""+s+"\" is not an integer.");
System.out.println(" Try again");
System.out.println("->"+e); // -> added to identify this line.
e.printStackTrace();
} // End of catch NumberFormatException
} // End of while loop
// End of main

Output

----jGRASP exec: java ExceptClass

Iteration 0: input is Hello and Tar Heel


Sorry, "Hello" is not an integer. Try again
->java.lang.NumberFormatException: For input string: "Hello"
java.lang.NumberFormatException: For input string: "Hello"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

at java.lang.Integer.parseInt(Integer.java:468)

at java.lang.Integer.parseInt(Integer.java:518)

at ExceptClass.main(ExceptClass.java:19)
Iteration 1: input is 23 and Strongbad
Sorry, "Strongbad" is not an integer. Try again
->java.lang.NumberFormatException: For input string: "Strongbad"
java.lang.NumberFormatException: For input string: "Strongbad"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

at java.lang.Integer.parseInt(Integer.java:468)

at java.lang.Integer.parseInt(Integer.java:518)

at ExceptClass.main(ExceptClass.java:21)
Iteration 2: input is 42 and 1234
Numbers are 42 and 1234.

----jGRASP: operation complete.

Potrebbero piacerti anche