Does a finally block always get executed in Java?

2018-12-31 01:15发布

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("i don't know if this will get printed out.");
}

30条回答
梦寄多情
2楼-- · 2018-12-31 01:48

I tried the above example with slight modification-

public static void main(final String[] args) {
    System.out.println(test());
}

public static int test() {
    int i = 0;
    try {
        i = 2;
        return i;
    } finally {
        i = 12;
        System.out.println("finally trumps return.");
    }
}

The above code outputs:

finally trumps return.
2

This is because when return i; is executed i has a value 2. After this the finally block is executed where 12 is assigned to i and then System.out out is executed.

After executing the finally block the try block returns 2, rather than returning 12, because this return statement is not executed again.

If you will debug this code in Eclipse then you'll get a feeling that after executing System.out of finally block the return statement of try block is executed again. But this is not the case. It simply returns the value 2.

查看更多
妖精总统
3楼-- · 2018-12-31 01:48

If an exception is thrown, finally runs. If an exception is not thrown, finally runs. If the exception is caught, finally runs. If the exception is not caught, finally runs.

Only time it does not run is when JVM exits.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 01:49

Because the final is always be called in whatever cases you have. You don't have exception, it is still called, catch exception, it is still called

查看更多
初与友歌
5楼-- · 2018-12-31 01:52

In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:

public static int getMonthsInYear() {
    try {
        return 10;
    }
    finally {
        return 12;
    }
}

Similarly, the following method does not throw an exception:

public static int getMonthsInYear() {
    try {
        throw new RuntimeException();
    }
    finally {
        return 12;
    }
}

While the following method does throw it:

public static int getMonthsInYear() {
    try {
        return 12;          
    }
    finally {
        throw new RuntimeException();
    }
}
查看更多
步步皆殇っ
6楼-- · 2018-12-31 01:53

Also a return in finally will throw away any exception. http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

查看更多
美炸的是我
7楼-- · 2018-12-31 01:54

Because a finally block will always be called unless you call System.exit() (or the thread crashes).

查看更多
登录 后发表回答