Sunday 9 April 2017

Java program which shows the use of finally block for handling exception

class ExceptionDemo
{
 public static void main(String args[])
 {
   try
   {
    int a,b;
    a=5;
    b=a/0;
   }
  catch(ArithmeticException e)
  {
   System.out.println("Divide by Zero\n");
  }
  System.out.println("...Executed catch statement");
 }
}




class ExceptionThrow
{
 public static void main(String args[])
 {
  try
  {
   throw new ArithmeticException("Testing Throw");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Caught exception: "+e);
  }
 }
}






class ExceptionProg
{
  static void fun(int a[]) throws ArrayIndexOutOfBoundsException
  {
    int c;
    try
    {
      c=a[0]/a[2];
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
     System.out.println("Caught exception: "+e);
    }
}
public static void main(String args[])
{
  int a[]={10,5};
  fun(a);
}
}



/*
This is a java program which shows the use of finally block for handling exception
*/
class finallyDemo
{
 public static void main(String args[])
 {
  int a=10,b=-1;
  try
  {
    b=a/0;
  }
  catch(ArithmeticException e)
  {
   System.out.println("In catch block: "+e);
  }
  finally
  {
   if(b!=-1)
      System.out.println("Finally block executes without occurrence of exception");
   else
     System.out.println("Finally block executes on occurrence of exception"); 
  }
 }
}