Exception Handling in JAVA

In this article you will learn what an exception is and how to handle it in various ways.

Introduction

You learn that there are three categories of errors : Syntax error, Runtime error and Logic error. A Syntax error arises because a rule of the language has not been followed; they are detected by the compiler. Runtime errors occur while the program is running, if the environment detects an operation that is impossible to carry out. A logic error occurs when the program does not perform the way it was intended to.

An exception is one of the abnormal conditions that can occur during the execution of a program. Exceptions are handled using an API which is given in java.lang package in the form of various Exception classes.

exceptFig1.gif

An exception can occur for many reasons; some of the general reasons are the following:

  1. A user has entered invalid data .
  2. A file needs to be opened but cannot be found.
  3. A network connection failed in the middle of communication

Catching an Exception

To catch an Exception in Java you need to use a try block with one or more catch clauses. In each catch clause you can define one specific type of exception that it is prepared to handle. You can put all the code in a try block that can potentially cause an exception to be generated.

Syntax 

  1. try  
  2. {  
  3.     // code that may cause of Exception  
  4. }  
  5. catch(......)  
  6. {  
  7.     //Code of handle the exception  
  8. }  

Note-you can have more than one catch block for a single try

Syntax

  1. try{  
  2.   
  3. // code that may cause of Exception  
  4.   
  5. }catch(......)//1  
  6. {  
  7. //Code of handle the exception  
  8. }  
  9.   
  10. catch(...2...)//2  
  11. {  
  12. //Code of handle the exception  
  13. }

Example

  1. class MultipleCatch  
  2. {  
  3.     public static void main(String arg[])  
  4.     {  
  5.             int a,x;  
  6.             try{  
  7.                 a = Integer.parseInt(arg[0]); // NumberFormat + ArrayIndex  
  8.                 x = 100 / a; // ArithmeticException  
  9.                 System.out.println("x = "+x);  
  10.                 }catch(ArithmeticException ex) // only for ArithmeticException  
  11.                         {  
  12.                      System.out.println("Ohh! sorry , this is / by 0 ");  
  13.                         }  
  14.                   catch(NumberFormatException ex) // only for NumberFormatException  
  15.                         {  
  16.                      System.out.println("invalid number for type casting , these alphabet");  
  17.                         }  
  18.                   catch(ArrayIndexOutOfBoundsException ex)  // only for ArrayIndexOutOfBoundsException  
  19.                       {  
  20.                     System.out.println("sorry there is no command line arguments");  
  21.                        }  
  22.            System.out.println("Thanxxxxxxxxxxxxxxxxxxx");  
  23.      }  
  24. }  
OUTPUT

multiplecatch.gif

Throwing exception

To throw an exception you simply use the throw with an object reference. All the methods use the throw statement to throw an exception.

Syntax

throw someThrowableObject ;

Example

  1. class UseThrow  
  2. {  
  3.     public static void main(String arg[])  
  4.     {  
  5.         int c=0;  
  6.         int a=Integer.parseInt(arg[0]);  
  7.         int b=Integer.parseInt(arg[1]);  
  8.         UseThrow ut=new UseThrow();  
  9.         try{  
  10.             c=a/b;  
  11.             throw new ArithmeticException();  
  12.         }catch (Exception e)  
  13.         {  
  14.             System.out.println(e);  
  15.         }  
  16.         System.out.println("the division = "+c);  
  17.     }  
  18. }  
OUTPUT

Usethrow.gif

Use of throws keyword

throws is keyword that is defined in Java. It is used for indicating that a particular method is throwing a particular type of exception while this method is in execution. When we use a throws clause in any method then it is the responsibility of the caller method which handle this exception with the help of putting it in try catch block.

Syntax

  1. public int div(int a, int b) throws AirthmeticException  
  2. {  
  3.     // body of methods  
  4. }

Example

  1. class MyThrows  
  2. {  
  3.     public void div() throws ArithmeticException   
  4.     {  
  5.         int a=1,b=0,c;  
  6.         c=a/b;  
  7.         System.out.println("now you are fine");  
  8.     }  
  9.     public static void main(String arg[])  
  10.     {  
  11.         MyThrows mt=new MyThrows();  
  12.         try{  
  13.             mt.div();  
  14.         }
  15.         catch(Exception e)  
  16.         {
  17.             System.out.println(e);  
  18.         }  
  19.     }  
  20. }  
OUTPUT

Mythrows.gif

Use of finally keyword

A finally block always executes when the try block exits. A finally block is used for whatever necessary code is needed, such as termination of a connection returning some value etc.

Syntax

  1. try{  
  2.   // code that may cause of Exception  
  3. }  
  4. finally{  
  5.         //Code  that is always  execute   
  6. }  
Syntax finally keyword with catch clause
  1. try{  
  2.     // code that may cause of Exception  
  3. }  
  4. catch(......)  
  5. {  
  6.      //Code of handle the exception  
  7. }  
  8. finally  
  9. {  
  10.      //Code  that is always  execute   
  11. }  

Example

  1. class Finally  
  2. {  
  3.   static int div(int a,int b)  
  4.     {  
  5.     return a/b;  
  6.     }    
  7.   public static void main(String ar[])   
  8.     {  
  9.      try{  
  10.            System.out.println(+div(4,5));  
  11.              }  
  12.     catch(Exception e)  
  13.             {  
  14.             System.out.println("Exception in main:"+e);  
  15.             }  
  16.     finally  
  17.         {  
  18.         System.out.println("I am always excute because we are in finally block");  
  19.         }  
  20.    }  
  21. }

OUTPUT

finally.gif