Exception Handling in Java

Java exception handling is a common coding practice. In this article, learn how to handle exceptions in Java.

Introduction

 
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 in Java 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 several 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 the communication.

Catching an Exception

 
To catch an exception in Java you need to use a try block with one or more catch blocks. 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 
 
try
{
      // code that may cause of Exception
}
catch(......)
{
      //Code of handling the exception
} 
 
Note-you can have more than one catch block for a single try.
 
Syntax
 
try{
      // code that may cause of Exception
}catch(......)//1
{
      //Code of handle the exception
}
catch(...2...)//2
{
      //Code of handle the exception
}
 
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
 
catching-an-exception 
 

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
 
public int div(int a, int b) throws AirthmeticException
   {
      // body of methods
   }
 
throw someThrowableObject ;
 
Example
  1. class UseThrow  
  2. {  
  3.     public static void main(String arg[])  
  4.     {  
  5.         int number = 2; 
  6.  
  7.         UseThrow ut=new UseThrow();  
  8.         try{  
  9.             c=number / 0;  
  10.             throw new ArithmeticException();  
  11.         }catch (Exception e)  
  12.         {  
  13.             System.out.println(e);  
  14.         }  
  15.         System.out.println("the division = "+number);  
  16.     }  
  17. }  
OUTPUT
 
throws-exception
 

Use of throws keyword

 
throws is a 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 handles this exception with the help of putting it in a try-catch block.
 
Syntax 
 
public int div(int a, int b) throws AirthmeticException
{
      // body of methods
}
 
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
 
throws-example 
 

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
 
try{
      // code that may cause of Exception
}
finally{
      // Code that always executed.
}
 
Syntax finally keyword with a catch clause
 
try{
      // code that may cause of Exception
}
catch(......)
{
      //Code of handle the exception
}
finally
{
      //Code that is always executed
}
 
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
 

Summary 

 
In this article, we learned about exception handling in Java and how to handle the exceptions in the Java programs.