Does a finally block always get executed in Java?

前端 未结 30 1560
逝去的感伤
逝去的感伤 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:53

    Adding to @vibhash's answer as no other answer explains what happens in the case of a mutable object like the one below.

    public static void main(String[] args) {
        System.out.println(test().toString());
    }
    
    public static StringBuffer test() {
        StringBuffer s = new StringBuffer();
        try {
            s.append("sb");
            return s;
        } finally {
            s.append("updated ");
        }
    }
    

    Will output

    sbupdated 
    

提交回复
热议问题