4

Possible Duplicate:
In Java, does return trump finally?

Wondering if finally statement will still get executed if it is after return statement?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

7 Answers7

14

Yes it will the only exception is System.exit(1) in try block

Umesh K
  • 13,436
  • 25
  • 87
  • 129
4

yes finally will get executed even if you return

public static void foo() {
        try {
            return;
        } finally {
            System.out.println("Finally..");
        }
    }

    public static void main(String[] args) {
        foo();
   }

Output:

Finally..
jmj
  • 237,923
  • 42
  • 401
  • 438
1

Not if the return statement is before its associated try block.

Yes if the return statement is inside the associated try block.

public void foo(int x)
{
    if (x < 0)
        return; // finally block won't be executed for negative values

    System.out.println("This message is never printed for negative input values");
    try
    { 
        System.out.println("Do something here");
        return;    
    }
    finally
    {
        System.out.println("This message is always printed as long as input is >= 0");
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Yes, finally will be executed though it is after return statement.

Hardik Mishra
  • 14,779
  • 9
  • 61
  • 96
0

Yes, ofcourse. Finally statement is designed to be executed in any cases if execution will go into try statement.

0

finally block will fail only when we terminate JVM by calling System.exit(int) or Runtime.getRuntime().exit(int).

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
0

On top of the other answers, if there is a return in your finally block, statements after the return will not be executed.

finally
    {
        System.out.println("In finally");
        if ( 1 == 1 )
            return;
        System.out.println("Won't get printed.);
    }

In the above snippet, "In finally" is displayed while "Won't get printed" isn't.

DaveH
  • 7,187
  • 5
  • 32
  • 53