java 7中再谈try catch
看输出:
Doing: Writing an article
Exception Message: Exception occured while doing work Exception Type: javaapplication4.ExceptionA
Closing the resource
Exception Message: Exception occured while closing Exception Type: javaapplication4.ExceptionB
再来看java 7中的新写法,代码如下:
输出结果为:
Listening to podcast
Res1 closing
Exception: Exception thrown while doing some work Thrown by: ExceptionA
大家可以思考下为什么这样输出,在新特性中,资源的自动关闭调用了close(),而
NewResource res = new NewResource("Res1 closing")){
已经为closingMessage赋值了,而最后的Exception e是输出了,suprred掉了
exception a和exception b的输出。
再看一个多层嵌套的try catch例子
输出:
Wow res getting res to do work
Nestedres closing
Res2 closing
Res1 closing
Exception: Exception thrown while doing some work Thrown by: ExceptionA
可以看到,后声明的资源上被最先CLOSE掉的,这里各自原先的exception都被supressed掉了。还可以用e.getSuppressed() 把屏蔽掉的exception都放来,比如
输出显示:
Wow res getting res to do work
Nestedres closing
Res2 closing
Res1 closing
Exception: Exception thrown while doing some work Thrown by: ExceptionA
Exception thrown while closing Class: ExceptionB
Exception thrown while closing Class: ExceptionB
Exception thrown while closing Class: ExceptionB