Gadgets

Tuesday, 8 March 2016

java program for exception handling mechanism

 Write a java program that describes the exception handling mechanism.

To handle exception we use try, catch, finally block. In try block we write risky code. If any exception will occur in try block, that exception handle in catch block. Try block will execute if exception is occur or not.
In this program we will get ArithmeticException in try block, we are handling that exception in catch block.
We will get output catch-finally block instead of try block.
public class ExceptionTest {
       public static void main(String[] args)
       {
              try
              {
                     int a=10;
                     int b=0;
                     int c=a/b;
                     System.out.println(c);
              }
              catch(ArithmeticException ae)
              {
                     System.out.println(10);                 
              }
              finally
              {
                     System.out.println("finally");
              }            
       }
}

OUTPUT:

/*
10
Finally
*/

No comments:

Post a Comment