Javac语法糖之TryCatchFinally

 

https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3

 

Optionally replace a try statement with the desugaring of a try-with-resources statement.  The canonical desugaring of
 try ResourceSpecification
   Block
is
 {
   final VariableModifiers_minus_final R #resource = Expression;
   Throwable #primaryException = null;

   try ResourceSpecificationtail
     Block
   catch (Throwable #t) {
     #primaryException = t;
     throw #t;
   } finally {
     if (#resource != null) {
       if (#primaryException != null) {
         try {
           #resource.close();
         } catch(Throwable #suppressedException) {
           #primaryException.addSuppressed(#suppressedException);
         }
       } else {
         #resource.close();
       }
     }
   }

 

举个解语法糖的例子,如下:

public class TryCatchFinally {
	public static void main(String[] args) {
		try (BufferedReader br = new BufferedReader(new FileReader("AutoCloseTest.java"));
				PrintStream ps = new PrintStream(new FileOutputStream("readme.txt"))) {
			System.out.println(br.readLine());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			System.out.println("default");
		}
	}
}  

 

 调用Lower类的visitTry()方法,传递的参数Tree如下截图所示。

 

final BufferedReader br = new BufferedReader(new FileReader("AutoCloseTest.java"));
/*synthetic*/ Throwable primaryException0$ = null;
try {
    final PrintStream ps = new PrintStream(new FileOutputStream("readme.txt"));
    /*synthetic*/ Throwable primaryException1$ = null;
    try {
        System.out.println(br.readLine());
    } catch (/*synthetic*/ final Throwable t$) {
        primaryException1$ = t$;
        throw t$;
    } finally {
        if (ps != null) 
        	if (primaryException1$ != null) try {
                    ps.close();
	        } catch (Throwable x2) {
	            primaryException1$.addSuppressed(x2);
	        } 
        else ps.close();
    }
} catch (/*synthetic*/ final Throwable t$) {
    primaryException0$ = t$;
    throw t$;
} finally {
    if (br != null)
    	if (primaryException0$ != null) try {
                br.close();
	    } catch (Throwable x2) {
	        primaryException0$.addSuppressed(x2);
	    } 
    else br.close();  

 由如上的代码可知,如果try块产生了异常,则会忽略close产生的异常(如果真的产生异常的话);否则才会抛出close产生的异常(如果真的产生异常的话)。

 

 

 

 

 

 

 

 

 

  

 

转载于:https://www.cnblogs.com/extjs4/p/7395704.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值