Wednesday, 5 February 2014

try-catch example


package com.naresh.exception;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExceptionHandlingExample {
      public static void main(String[] mnb) {
            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);
            }
      }

}
Output

Execute ExceptionHandlingExample 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


No comments:

Post a Comment