Exception Handling: try-catch example
package com.ram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExceptionHandlingExample1 {
public static void main(String[] args){
int a, b, c;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter value for a :: ");
a = Integer.parseInt(br.readLine());
System.out.print("Enter value for b :: ");
b = Integer.parseInt(br.readLine());
c = a / b;
System.out.println("C = "+c);
}
catch(ArithmeticException ae){
System.out.println("An ArithmeticException occured = "+ae);
}
catch(Exception e){
System.out.println("Any other exception "+e);
}
}
}
Execute ExceptionHandlingExample1 class and user would be prompted to enter two values.
To check for exception, enter "0" for variable "b"
Enter value for a :: 30
Enter value for b :: 0
An ArithmeticException occured = java.lang.ArithmeticException: / by zero
To check for exception, enter "0" for variable "b"
Enter value for a :: 30
Enter value for b :: 0
An ArithmeticException occured = java.lang.ArithmeticException: / by zero
No comments:
Post a Comment