Does a finally block always get executed in Java?

前端 未结 30 2145
逝去的感伤
逝去的感伤 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:48

    Consider the following program:

    public class SomeTest {
    
        private static StringBuilder sb = new StringBuilder();
    
        public static void main(String args[]) {
    
            System.out.println(someString());
            System.out.println("---AGAIN---");
            System.out.println(someString());
            System.out.println("---PRINT THE RESULT---");
            System.out.println(sb.toString());
        }
    
        private static String someString() {
    
            try {
                sb.append("-abc-");
                return sb.toString();
    
            } finally {
                sb.append("xyz");
            }
        }
    }
    

    As of Java 1.8.162, the above code block gives the following output:

    -abc-
    ---AGAIN---
    -abc-xyz-abc-
    ---PRINT THE RESULT---
    -abc-xyz-abc-xyz
    

    this means that using finally to free up objects is a good practice like the following code:

    private static String someString() {
    
        StringBuilder sb = new StringBuilder();
    
        try {
            sb.append("abc");
            return sb.toString();
    
        } finally {
            sb = null; // Just an example, but you can close streams or DB connections this way.
        }
    }
    

提交回复
热议问题