java finally中含return语句

《java核心技术卷一》中提到过:当finally子句包含return 语句时(当然在设计原则上是不允许在finally块中抛出异常或者 执行return语句的,我不明白为何java的设计者并没有在语法上禁用这样的形式),将会出现一种意想不到的结果。假设利用return语句从try 语句块中退出。在方法返回前,finally子句的内容将被执行。如果finally子句中也有一个return语句,这个返回值将会覆盖原始的返回值。

但作者没有提及的是,finally中的return语句不仅会覆盖原返回值,还会”吃掉“在catch子句中抛出的异常。测试代码如下:

import java.io.*;

public class ReturnInFinally{
	public static void main(String[] args){
		try{
			boolean i=Test1();
			System.out.println("End of try Test1");
		}catch(Exception ex){
			System.out.println("Catch exception in Main() ");
		}finally{
			System.out.println("Finally in Main() ");
		}
		
		boolean j=Test2();
		System.out.println("j=" + j);
	}
	private static boolean Test1() throws Exception{
		try{
			throw new Exception("Exception thrown by Test1()");
		}catch(Exception ex){
			System.out.println("Catch exception in Test1() ");
			throw ex;//重新抛出异常
		}finally{
			return true;//抛出的异常被return”吃“掉
		}
	}
	private static boolean Test2(){
		try{
			return false;
		}finally{
			return true;
		}
	}
}

  

运行结果为:

Catch exception in Test1() 
End of try Test1
Finally in Main() 
j=true

最近接触到一些字节码修改的东西,发现finally的实现是通过将finally块加在return,re-throw语句之前,使得finally在结束try-catch块的时候总能被执行。

  

原文地址:https://www.cnblogs.com/mosmith/p/4165842.html