Exception handling example

In the following example code you will see that how the exception handling can be done in java program. This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.

import java.io.*;
public class exceptionHandle{
public static void main(String[] args) throws Exception{
try{
int a,b,c;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Two numbers :");
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
c=a+b;
System.out.println(a+"+"+b+"="+c);
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()
+ " is not a numeric value.");
System.exit(0);
}
}
}
Output

Enter the Numbers:
2 a
For input string 'a' is not numeric value
 


java NumberFormatException exception handling example output



0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org