Does a finally block always get executed in Java?

前端 未结 30 1633
逝去的感伤
逝去的感伤 2020-11-21 07:24

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

try         


        
30条回答
  •  猫巷女王i
    2020-11-21 07:46

    Finally is always run that's the whole point, just because it appears in the code after the return doesn't mean that that's how it's implemented. The Java runtime has the responsibility to run this code when exiting the try block.

    For example if you have the following:

    int foo() { 
        try {
            return 42;
        }
        finally {
            System.out.println("done");
        }
    }
    

    The runtime will generate something like this:

    int foo() {
        int ret = 42;
        System.out.println("done");
        return 42;
    }
    

    If an uncaught exception is thrown the finally block will run and the exception will continue propagating.

提交回复
热议问题