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.
Output
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);
}
}
}
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);
}
}
}
Enter the Numbers:
2 a
For input string 'a' is not numeric value
0 comments:
Post a Comment