开发者

Will the statements inside finally get executed if they are following return? [duplicate]

开发者 https://www.devze.com 2023-02-16 23:05 出处:网络
This question already has answers here: 开发者_JAVA技巧 Closed 10 years ago. Possible Duplicate: In Java, does return trump finally?
This question already has answers here: 开发者_JAVA技巧 Closed 10 years ago.

Possible Duplicate:

In Java, does return trump finally?

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


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


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..


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");
    }
}


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号