3

I don't get why is the statement in finally block being executed despite using return statement in try block. The return statement, as i know, returns the execution to the main.

If am using return in try block that means execution of try ends at that point and control goes into the main. Then why statement in finally is executed?

class a
{
 public static void main(String arr[])

{    
 try
 {
 System.out.println("hello1");
 return;
 }

    finally
    {
    System.out.println("hello2");

    }

}
}
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
MANU
  • 1,358
  • 1
  • 16
  • 29

4 Answers4

3

Regardless of what you are doing in try, the finally block always executes even though you return from your try block.

From finally docs

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.

Fun learning: As you are talking about return and try-finally. Just put return in try and again return in finally. And see what happens :)

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 1
    @IRON-MAN, Re fun learning: Also fun to see what happens if the try block throws an exception that is not caught in any catch block _and_ the finally also throws an exception. Hint: Allowing a finally block to throw is considered to be Bad Style. – Solomon Slow Sep 05 '14 at 13:47
  • 1
    Have even more fun: see what happens if you use System.Exit. – Bathsheba Sep 05 '14 at 13:49
  • @Bathsheba My god. I killed JVM. Police on their way ;). – Suresh Atta Sep 05 '14 at 14:01
3

Because that's what it's designed to do. It is not like catch (...) in C++ (which only executes if not caught elsewhere).

finally can be very useful in cleaning up resources: it is one way that Java introduces RAII-type features that are more prevalent in other languages like C++ (via destructors). Java more naturally performs clean-up via the garbage collector but finally permits an alternative approach.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Finally will always execute. You could try using some conditional (if, else) statements instead.

Celt
  • 2,469
  • 2
  • 26
  • 43
0

why is the statement in finally block executed despite using return in try block

By design. The whole point of a finally block is that it doesn't matter how you leave the try block, the code in finally will be run. Full stop. (Well, unless you crash the JVM.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875