Pages

Wednesday 9 October 2013

Exception handling in java



Exception: 
          They are the undesirable or abnormal conditions that arise in code fragments of any program at run-time. They can also be called as run-time errors. The exceptions terminate the normal operation of a program. So it becomes necessary to manage and handle the exceptions. Yes! Java provides us with some effective mechanism to handle the exceptions.


Note to not note down: Don’t you think? Java is so kind! It gives solution for every difficulty while coding, for free!!


          Exception in Java is an object which is used to describe undesired or abnormal conditions that will occur during the execution of a code sequence at run-time. There is a built-in class called throwable in Java. All exception types have to be subclass to the throwable class. Throwable class has two immediate subclasses named, exception and error.





          Before we handle exception ourselves we will see how java will handle this exception by default. The Java is capable of handling exception by itself by using its default exception handler. Consider the below program example which generates the divide by zero exception. This exception is of the type Arithmetic exception which is subclass of class Exception. 

package blog.exception.handler;



public class Xexception

{

   public static void main(String[] args)

   {

       int a=10,b=0,div;

      

       div=a/b; // control is transferred to the default exception handler.  

      

       System.out.println("divide reult"+div);//this will not be executed.

      

      

   }

}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

     at blog.exception.handler.Xexception.main(Xexception.java:9)



     In the above example program when ‘div=a/b;’ line is executed then the control is transferred to the default exception handler of Java. And stack trace is printed as shown in the output. 

          The below mentioned are the important keywords to remember, which will be helpful for us to manage and handle exceptions in Java.


1.     try

2.     catch

3.     throw

4.     throws

5.     finally


          One by one we will discuss the usage of these keywords to manage and handle the exception. 

Try and Catch Block:
           The try and catch keywords are always used together to handle exceptions in Java. Both these keywords together constitute try and catch blocks, which is Java’s most efficient mechanism to tackle exceptions. The general form of try and catch blocks are shown below.

                  try {

               // code that you want to check for exception

             }

         catch (exception_type ex_variable)

             {  

               //body of catch

             }

  Note: A try block must always be followed by a catch block or finally block.


            How to use try and catch blocks to handle exception?


            It is very easy to implement the try and catch block. Just follow the instructions below.


1.     You should enclose the code sequence that you want to check for exception in the try block body.


2.     Immediately after the try block, include the catch block with specification of the exception type that you want to catch. You can also use the print statements to describe the exception caught. 


           The simple example program implementing try and catch blocks is shown below to handle the exception of type ArithmeticException, ‘divide by zero’.

package blog.exception.handler;



public class Xexception

{

   public static void main(String[] args)

   {

     try

      { 

       int a=10,b=0,div;

      

       div=a/b; // control is transferred to the catch block.  

      

       System.out.println("divide reult"+div);//this will not be executed.

      }

     catch(ArithmeticException ex)

     {

           System.out.println("Divide by zero");

           System.out.println();

           System.out.println(ex);//exception description returned by the toString() method.

     }

   }

}

Output:

Divide by zero



java.lang.ArithmeticException: / by zero

Note: The throwable class overrides the toString() method defined by the Object class so that it can return a string that describes the exception.


Note: Object class is superclass of every class in Java.



A try can have more than one catch!! :

           There will be situation in which one code can generate more than one exception. In order to handle all the exceptions, a try block will be sometimes implemented with multiple catch blocks.


           In the below example program a try block with two catch statements are shown: 


package blog.exception.handler;



public class Xexception

{

   void ExcpMethod(int x)

   {

     try

      { 

           if(x==0)

           {

           int a=10,b=0,div;

           div=a/b;  

           }

          

           if(x==1)

           {

                int a[]=new int[2];

                a[4]=11;

           }

        

           if(x==2)

           {

                int b[]=new int[-2];

                b[1]=10;

           }

      }

     catch(ArithmeticException ex)

     {

           System.out.println(ex);//exception description returned by the toString method.

           System.out.println();

     }

     catch(ArrayIndexOutOfBoundsException ex)

     {

           ex.printStackTrace();

           System.out.println();

     }

     catch(Exception ex)

     {

           ex.printStackTrace();

           System.out.println();

     }

   }

}

package blog.exception.handler;



public class DemoXexception

{

  public static void main(String[] args)

  {

     Xexception xe=new Xexception();

    

     xe.ExcpMethod(0);

     xe.ExcpMethod(1);

     xe.ExcpMethod(2);

  }

}

Output:

java.lang.ArrayIndexOutOfBoundsException: 4



java.lang.ArithmeticException: / by zero

     at blog.exception.handler.Xexception.ExcpMethod(Xexception.java:18)

     at blog.exception.handler.DemoXexception.main(DemoXexception.java:10)



java.lang.NegativeArraySizeException

     at blog.exception.handler.Xexception.ExcpMethod(Xexception.java:23)

     at blog.exception.handler.DemoXexception.main(DemoXexception.java:11)


           The catch block is executed in sequence from first catch block to the last catch block. So when you implement a try block with multiple catch blocks always remember to place the exception subclasses before any of their superclasses. You can see in the above example program, the ‘ArithmeticException’ containing catch block is placed before the catch block containing ‘Exception’. This is done to ensure that no superclass is executed before any of its subclasses.


           If suppose a superclass catch block is executed before its subclasses, the subclass catch block is never reached because superclass can handle all its subclass exceptions. The unreached code in Java results in error. In this case program will not compile.

Try Block can be nested: 

         A try block inside a try block forms nested try. The below example program shows you the implementations of nested try block.

package blog.exception.handler;



public class Xexception

{

   void ExcpMethod(int x)

   {

     try

      {

           if(x==1)

           {

                int a[]=new int[2];

                a[4]=11;

           }

          

        try

        {

              if(x==0)

              {

             int a=10,b=0,div;

             div=a/b;  

              }

        }

        catch(ArrayIndexOutOfBoundsException ex)

        {

                ex.printStackTrace();

        }

        

      }

     catch(ArithmeticException ex)

     {

           System.out.println(ex);//exception description returned by the toString method.

     }

    

   }

}

package blog.exception.handler;



public class DemoXexception

{

  public static void main(String[] args)

  {

     Xexception xe=new Xexception();

    

     xe.ExcpMethod(0);

     xe.ExcpMethod(1);

  }

}

Output:

java.lang.ArithmeticException: / by zero



Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

      at blog.exception.handler.Xexception.ExcpMethod(Xexception.java:12)

      at blog.exception.handler.DemoXexception.main(DemoXexception.java:10)

The throw keyword: 

         It is possible for any program to throw exceptions explicitly by using throw keyword. The general form of throw statement is shown below: 


             throw ThrowableTypeObject;


         The ‘ThrowableTypeObjectin throw statement has to be an object of type Throwable class or the subclass of Throwable class. Consider the below program example that illustrates the use of throw keyword.

package blog.exception.handler;



public class ThrowKeywordX

{

  void XThrowMethod()

  {

       try

       {

             throw new SecurityException("security voilation attempted");

       }

       catch(SecurityException ex)

       {

             System.out.println("first catch in XThrowMethod()");

             System.out.println(ex);

             throw ex;

       }

  }

 

}



package blog.exception.handler;



public class DemoXexception

{



       public static void main(String[] args)

       {

           ThrowKeywordX thx=new ThrowKeywordX(); 

           try

           {

                thx.XThrowMethod();

           }

           catch(SecurityException ex)

           {

                System.out.println();

                System.out.println("Second catch in main method");

                System.out.println(ex);

           }

       }

}



Output:

first catch in XThrowMethod()

java.lang.SecurityException: security voilation attempted



Second catch in main method

java.lang.SecurityException: security voilation attempted

    The program execution flow is terminated immediately after the throw statement is executed. The nearest try blocks are checked for the catch statements which can match with the exception thrown. If match found then it is transferred to that try block or else the default exception handler will take care of the exception.


The Throws keyword: 

         In many cases methods may cause exceptions that it will not handle. In such cases those methods have to provide details of the exceptions that it might cause, by using throws keyword. So that callers of these methods protect themselves against those exceptions. Not using throws keyword in above cases will cause compile error.


        The general form of using throws keyword is as shown below: 

          Type methodName(parameter-list) throws exception-list

     {

        //body of method

     }

    The exception-list in general form is the comma separated list of exceptions that a method can throw. Consider the below example program showing implementation of throws keyword.

package blog.exception.handler;



public class ThrowKeywordX

{

  static void XThrowMethod()throws SecurityException //throws keyword

  {

      System.out.println("Am XThrowMethod()");

      throw new SecurityException("security voilation attempted");

      

  }

 

}

package blog.exception.handler;



public class DemoXexception

{



       public static void main(String[] args)

       { 

           try

           {

                ThrowKeywordX.XThrowMethod();

           }

           catch(SecurityException ex)

           {

                System.out.println();

                System.out.println("Am main method");

                System.out.println(ex);

           }

       }

}

Output:

Am XThrowMethod()



Am main method

java.lang.SecurityException: security voilation attempted.


The finally keyword:


           The finally keyword forms a block of code in Java. It is placed after the try block. This block will be executed in any condition whether the exception has occurred or not. It will be executed even if a return statement is present in try block. Before the control is transferred to the calling method the finally is executed.


           Consider the below program example illustrating the finally block using three cases of its execution.

package blog.exception.handler;



public class ThrowKeywordX

{

  static void methodA()

  {

      try //exception case

      {

      throw new SecurityException("security voilation attempted");

      }

      catch(Exception ex)

      {

            System.out.println(ex);

      }

      finally

      {

            System.out.println("am finally in methodA()");

            System.out.println();

      }

  }

 

  static void methodB() //retrun case

  {

       try

       {

             return; //return to the calling method.

       }

       finally

       {

             System.out.println("am finally in method B");

             System.out.println();

       }

  }

   static void methodC()//noraml case

   {

        try

        {

              System.out.println("normal case");

        }

        finally

        {

              System.out.println("A finally in method C");

        }

   }

}

  

package blog.exception.handler;



public class DemoXexception

{



       public static void main(String[] args)

       { 

           ThrowKeywordX.methodA();

           ThrowKeywordX.methodB();

           ThrowKeywordX.methodC();

       }

}



Output:  

java.lang.SecurityException: security voilation attempted

am finally in methodA()



am finally in method B



normal case

am finally in method C
 
          In my next post the exception handling will be continued with topics: Java’s built-in Exceptions, creating your own subclasses of exception and chained exceptions.