本文为原创文章,转载请注明出处
查看[Java]系列内容请点击:https://www.jianshu.com/nb/45938443
当我们在通过try-with-resource
语法进行资源关闭的时候,那么:
try-with-resource
会优先执行隐含的finally
代码!!!
即使你已经显式的写了finally
,编译器还是会生成一个优先执行close()
的finally
看下面示例:
public class MainTest {
public static void main(String[] args) {
MyClass c = new MyClass();
try (c) {
System.out.println("in try clause.");
throw new Exception();
} catch (Exception e) {
System.out.println("in catch clause.");
} finally {
System.out.println("in finally.");
}
}
private static class MyClass implements Closeable {
@Override
public void close() {
System.out.println("closed.");
}
}
}
输出结果:
in try clause.
closed.
in catch clause.
in finally.
可以看到,系统首先执行了try
代码块,然后在抛出异常的时候立即执行了close()
操作,然后再执行catch
代码块,最后执行我们自己定义的finally
。
这点一定要注意,很容易出现暗坑!!!特别是你想在catch
中在close()
操作之前执行一些操作的时候,一定要注意!!!
网友评论