Saturday, December 24, 2011

Multiple Catch Block in JAVA

In this Example i have used Arithmetic and NumberFormat Exception, and also Finally keyword


Arithmetic Exception:
This Exception is thrown when any Arithmetic Error occur such as dividing number by 0


NumberFormat Exception:
NumberFormatException is a subclass of the Runtime Exception class.  A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values. 


Finally : 
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a returncontinue, or break.




Example

import java.io.*;
import java.lang.*;
public class MultiCatch
{
          public static void main(String args[])
          {
                    int a,b;
                    try
                    {
                          a=Integer.parseInt(args[0]);
                          b=100/a;
                          System.out.println("Division:"+ b);


                    }
                   catch(ArithmeticException e)
                    { 
                       System.out.println("Division by zero.." );
                    }
                   catch(NumberFormatException e)
                    {
                      System.out.println("Not a Number.." );   
                    }
                  finally
                   {
                      System.out.println("Always executes " );
                   }
          }


}

No comments:

Post a Comment