Try to Catch Finally

I have read many questions on stackOverFlow about behavior and confusion about exception handling mechanism. Here I will discuss some of the important points related to try-catch and finally.

Many of the developers leave in a dark without knowing the actual behavior of this exception handling mechanism. For the proper declaration of try-catch-finally It works in a sequence stated below.

tryCatchIt goes this way, if try block raise exception catch will handle it and finally will be executed at last and if try does not raise any exception it will directly execute finally block as there is no exception to catch. Now in both case finally will get executed for sure if one of the following does not occur,

  • For some reason JVM Crashed before execution of finally
  • If current thread is interrupted by some other thread
  • System.exit() in try block

Now finally is a kind of mandatory block of code that must be executed for any case no matter what happened in try and catch (except for above stated scenarios). It simply executed after the execution of try and catch(if exception occur). It is also possible to exclude the catch block (definitely not recommended) you can have try with finally only. consider following valid declarations.

  try {
    System.out.println("Inside try Block.");
    int a = 0;
    int b = 100/a;
 } catch (ArithmeticException e) {
    System.out.println("Inside catch Block.");
 } finally {
    System.out.println("Inside finally Block.");
 }

You will have following output :

Inside try Block.
Inside catch Block.
Inside finally Block.

Now you can just remove the catch block and you can still have try with finally which is also completely valid declaration as stated below but it will not be able to handle exception raised by the try and simply throw Exception, same way as any block of code can throw and as you may have to handle this ArithmeticException properly or JVM will manage to handle it at last.

  try {
    System.out.println("Inside try Block.");
    int a = 0;
    int b = 100/a;
 } finally {
    System.out.println("Inside finally Block.");
 }

and you will have following output (Output may vary due to buffered println method) ,

Inside try Block.
Inside finally Block.
Exception in thread “main” java.lang.ArithmeticException: / by zero
at TryDemo.main(TryDemo.java:24)

As you can see try has thrown the Exception which is not handled in our case.

Use of finally : finally block is created to do some work after the try no matter try failed or succeed. So basically it should end up with some stuff like closing the resources used in the try block i.e. input streams.

Now you may ask what if finally contains return statement. Consider following example for that,

public class TryToCatchFinally {

 public static int getValidResult() {
     try {
       System.out.println("Inside try..");
       return 1;
     } catch (Exception e) {
        System.out.println("Inside catch..");
     } finally {
        return -1;//Compiler will warn you about this
        //finally block does not complete normally
     }
 }

 public static void main(String[] args) {
     int validResult = getValidResult();
     System.out.println(validResult);
 }

}

and you will have following output :

Inside try..
-1

So, finally is the block which will execute no matter what happened in try and catch. Even though it’s a bad practice to put return statement in the finally block. Few more points remains as why it’s bad practice to return from finally block ?, is it good to throw exception from finally ? etc. that we will discuss later.

NOTE : return statement of try or catch is discarded during execution if the subsequent finally block contains return statement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s