return 与 finally 的执行顺序对返回值的影响

return 与 finally 的执行顺序对返回值的影响

 

对于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
 

你真的了解try{ return }finally{}中的return?
Java虚拟机规范
java 官方教程的finally语句

上一篇:基于JRebel开发的MySQL Explain插件


下一篇:confluent-ksql 学习