对于 try 和 finally 至少一个语句块包含 return 语句的情况:
finally 语句块会执行
finally 没有 return,finally 对 return 变量的重新赋值修改无效
try 和 finally 都包含return,return 值会以 finally 语句块 return 值为准

代码

public static void main(String[] args) {
        System.out.println(getString());
    }
    
    public static String getString() {
        String str = "A";
        try {
            str = "B";
            return str;
        } finally {
            System.out.println("finally change return string to C");
            str = "C";
//            return str;
        }
    }

输出

finally change return string to C
B

public static void main(String[] args) {
        System.out.println(getString());
    }
    
    public static String getString() {
        String str = "A";
        try {
            str = "B";
            return str;
        } finally {
            System.out.println("finally change return string to C");
            str = "C";
            return str;
        }
    }

输出

finally change return string to C
C
————————————————
版权声明:本文为CSDN博主「ConstXiong」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/meism5/...


书写人生
65 声望3 粉丝