Exception handling constructs

Exception Handling Mechanism

In java, exception handling is done using five keywords,
  1. try
  2. catch
  3. throw
  4. throws
  5. finally
Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occurs.

Using try and catch

Try is used to guard a block of code in which exception may occur. This block of code is called guarded region. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it.

Example using Try and catch

class Excp
{
 public static void main(String args[])
 {
  int a,b,c;
  try
  {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero"); 
  }
  System.out.println("After exception is handled");
 }
}
Output :
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line "After exception is handled" is printed.

Multiple catch blocks:

A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.

Example for Multiple Catch blocks

class Excep
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  } 
  catch(ArithmeticException ae)
  {
   System.out.println("divide by zero");
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
 }
}
Output :
divide by zero

Example for Unreachable Catch block

While using multiple catch statements, it is important to remember that exception sub classes inside catchmust come before any of their super classes otherwise it will lead to compile time error.
class Excep
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  }
  catch(Exception e)    //This block handles all Exception
  {
   System.out.println("Generic exception");
  }
  catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
  {
   System.out.println("array index out of bound exception");
  }
 }
}

Nested try statement

try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catchhandler for a particular exception then the outer try is checked for match.
class Excep
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={5,0,1,2};
   try
   {
    int x=arr[3]/arr[1];
   }
   catch(ArithmeticException ae)
   {
    System.out.println("divide by zero");
   }
   arr[4]=3;
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
 }
}

Important points to Remember

  1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
  2. Super class Throwable overrides toString() function, to display error message in form of string.
  3. While using multiple catch block, always make sure that exception subclasses comes before any of their super classes. Else you will get compile time error.
  4. In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try, if required.
  5. Only the object of Throwable class or its subclasses can be thrown.

throw Keyword

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance

Creating Instance of Throwable class

There are two possible ways to get an instance of class Throwable,
  1. Using a parameter in catch block.
  2. Creating instance with new operator.
    new NullPointerException("test");
    
    This constructs an instance of NullPointerException with name test.

Example demonstrating throw Keyword

class Test
{
 static void avg() 
 {
  try
  {
   throw new ArithmeticException("demo");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Exception caught");
  } 
 }

 public static void main(String args[])
 {
  avg(); 
 }
}
In the above example the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.

throws Keyword

Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
 //definition of method
}

NOTE : It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their subclass.

Example demonstrating throws Keyword

class Test
{
 static void check() throws ArithmeticException
 {
  System.out.println("Inside check function");
  throw new ArithmeticException("demo");
 }

 public static void main(String args[])
 {
  try
  {
   check();
  }
  catch(ArithmeticException e)
  {
   System.out.println("caught" + e);
  }
 }
}

finally clause

A finally keyword is used to create a block of code that follows a try block. A finally block of code always executes whether or not exception has occurred. Using a finally block, lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block.
finally clause in exception handling in java

Example demonstrating finally Clause

Class ExceptionTest
{
 public static void main(String[] args)
 {
  int a[]= new int[2];
  System.out.println("out of try");
  try 
  {
   System.out.println("Access invalid element"+ a[3]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally 
  {
   System.out.println("finally is always executed.");
  }
 }
}
Output :
Out of try
finally is always executed. 
Exception in thread main java. Lang. exception array Index out of bound exception.  
You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.

No comments:

Post a Comment