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
  • 79,431
  • 144
  • 301
  • 419

7 Answers7

14

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

Umesh K
  • 12,846
  • 22
  • 85
  • 126
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
  • 232,312
  • 42
  • 391
  • 431
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
  • 299,921
  • 44
  • 364
  • 552
0

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

Hardik Mishra
  • 14,479
  • 9
  • 59
  • 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
  • 60,780
  • 12
  • 83
  • 92
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,043
  • 5
  • 30
  • 51