Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the gist of finally block in Java?

I think on the following examples; but could not figure out what the importance of the finally block is. Can you tell me the difference of the executions of these two code samples? Also a real life example can be helpful.

Sample 1:

    try{
       // some code 1
    }catch(Exception ex){
       // print exception   
    }finally{
       // some code 2            
    }

Sample 2:

    try{
      // some code 1
    }catch(Exception ex){
      // print exception   
    }
    // some code 2
like image 956
abuzittin Avatar asked Jun 30 '10 08:06

abuzittin


2 Answers

There is a big difference in the two snippets you've presented, e.g. when the catch block itself throws an exception, the finally block would still be executed by its semantics.

That is the following snippet prints "Finally!", but not "What about me???":

    try {
        throw null;     // throws NullPointerException!
    } catch (Exception e) {
        int oops = 1/0; // throws ArithmeticException!
    } finally {
        System.out.println("Finally!"); // still gets executed!
    }
    System.out.println("What about me???"); // doesn't get executed!

Generally speaking, the finally of a try block practically always gets executed. There's no such guarantee for any code following the try block.


But what if my catch block is just a simple print statement?

There's still no guarantee that it won't throw something. Something could still go wrong in e.g. the construction for the exception detailed message.

Even if you make a best effort guarantee that the catch code is "safe" and the code following the try statement will always be executed, the question then becomes "Why?". Why avoid finally but then try so hard to replicate its semantics?

finally semantics is guaranteed, requiring no burden of proof from either the writer or the reader of the code. Precisely because of this, it's idiomatic to use finally block to put mandatory "clean-up" code. Using finally guarantees correctness and enhance both writability and readability.

like image 136
polygenelubricants Avatar answered Oct 01 '22 19:10

polygenelubricants


The finally block is executed even if e.g. an Error is thrown, which is not caught by the catch block in your example. So you can put cleanup code in the finally block, which should be run always, regardless of the outcome of the operations in the try and catch blocks.

Note that usually catch blocks catch more specific types of exceptions - often only checked exceptions -, so in most cases the difference between the two code examples above is very definite.

Update: you may say that your catch block can never throw an exception, so finally is not needed. However, note two things:

  • this is only the current state of the code, and it can change in the future - can you guarantee that the future programmer who adds some potentially exception-throwing code in the catch block, will remember to put the cleanup code after it into a finally block?
  • try-catch-finally is a programming idiom which makes it easier for people reading the code to understand what's going on. If you don't use the common idiom, you risk misunderstanding, thus bugs on the long term.
like image 35
Péter Török Avatar answered Oct 01 '22 17:10

Péter Török