实现了AutoCloseable接口的类,可以在try的时候直接实例化对象。try代码块完成之后,自动调用close方法,相当于在finally里主动调用。但是出现异常后的流程和try finally有什么不同呢? 下面写代码测试一下。

首先定义一个类Cat,实现AutoCloseable接口

class Cat implements AutoCloseable{
void sayHello() throws Exception {
Utils.println("calling sayHello(), I will throw an exception");
throw new Exception("Exception in sayHello() ");
} @Override
public void close() throws Exception {
Utils.println("I'm closing, I will throw an exception");
throw new Exception("Exception in close()");
}
}

我们的这个Cat有以下特点:

  • sayHello方法会抛出异常
  • close方法也会抛出异常

test v1: 'try(Cat cat = new Cat())' VS 'try finally'

没有catch(不要被外层的catch迷惑,那只是为了打印异常)

static void testV1(){
Utils.println("----try(Cat cat = new Cat())-----");
try{
try(Cat cat = new Cat()){
cat.sayHello();
} }catch (Exception e){
Utils.println("cache error in main (" + e + "), let's see its stack trace");
Utils.printStackTrace(e);
}
Utils.println("--------------"); Utils.println("----try finally-----");
try{
Cat cat = null;
try{
cat = new Cat();
cat.sayHello();
}finally {
if(cat != null){
cat.close();
}
}
}catch (Exception e){
Utils.println("cache error in main (" + e + "), let's see its stack trace");
Utils.printStackTrace(e);
}
Utils.println("--------------");
}

结果输出:

----test v1----------------------------------------
----try(Cat cat = new Cat())-----
calling sayHello(), I will throw an exception
I'm closing, I will throw an exception
cache error in main (java.lang.Exception: Exception in sayHello() ), let's see its stack trace
java.lang.Exception: Exception in sayHello()
at Cat.sayHello(Cat.java:4)
at Test.testV1(Test.java:16)
at Test.main(Test.java:4)
Suppressed: java.lang.Exception: Exception in close()
at Cat.close(Cat.java:10)
at Test.testV1(Test.java:17)
... 1 more
--------------
----try finally-----
calling sayHello(), I will throw an exception
I'm closing, I will throw an exception
cache error in main (java.lang.Exception: Exception in close()), let's see its stack trace
java.lang.Exception: Exception in close()
at Cat.close(Cat.java:10)
at Test.testV1(Test.java:33)
at Test.main(Test.java:4)
--------------

结论

  • try(Cat cat = new Cat())

    • try代码块完成之后会自动调用close
    • close抛出的异常,被Suppressed了,外层捕获的只有sayHello的异常,但通过堆栈可以找到这个Suppressed的异常
  • try finally
    • 外层捕获的是在finally执行close时抛出的异常,sayHello的异常完全不见了。

test v2: 'try(Cat cat = new Cat()) catch{}' VS 'try catch finally'

有catch,并且catch里再抛出异常

static void testV2(){
Utils.println("----try(Cat cat = new Cat()) catch-----");
try{
try(Cat cat = new Cat()){
cat.sayHello();
} catch (Exception e) {
Utils.println("cached err (" + e.getMessage() + "), I will throw an exception again");
throw new Exception("Exception in catch", e);
} }catch (Exception e){
Utils.println("cache error in main (" + e + "), let's see its stack trace");
Utils.printStackTrace(e);
}
Utils.println("-----------------------------------------"); Utils.println("----try catch finally--------------------");
try{
Cat cat = null;
try{
cat = new Cat();
cat.sayHello();
} catch (Exception e) {
Utils.println("cached err (" + e.getMessage() + "), I will throw an exception again");
throw new Exception("Exception in catch", e);
}finally {
if(cat != null){
cat.close();
}
}
}catch (Exception e){
Utils.println("cache error in main (" + e + "), let's see its stack trace");
Utils.printStackTrace(e);
}
Utils.println("-------------------------------------------");
}

结果输出

----test v2------
----try(Cat cat = new Cat()){} catch{}-----
calling sayHello(), I will throw an exception
I'm closing, I will throw an exception
cached err (Exception in sayHello() ), I will throw an exception again
cache error in main (java.lang.Exception: Exception in catch), let's see its stack trace
java.lang.Exception: Exception in catch
at Test.testV2(Test.java:50)
at Test.main(Test.java:8)
-----------------------------------------
----try catch finally--------------------
calling sayHello(), I will throw an exception
cached err (Exception in sayHello() ), I will throw an exception again
I'm closing, I will throw an exception
cache error in main (java.lang.Exception: Exception in close()), let's see its stack trace
java.lang.Exception: Exception in close()
at Cat.close(Cat.java:10)
at Test.testV2(Test.java:70)
at Test.main(Test.java:8)
-------------------------------------------
---------------------------------------------------------------------

结论

  • try(Cat cat = new Cat()) catch

    • catch之前就调用了close(符合try代码块完成之后会自动调用close这个结论)
    • catch到的是sayHello的异常,close抛出的异常依然被Suppressed了
    • catch中再次抛出的异常被外层捕获
  • try catch finally
    • 先走catch,再走finally,所以catch捕获的是sayHello的异常
    • catch中再次抛出的异常不见了,外层捕获的是在finally执行close时抛出的异常。

测试代码地址:https://github.com/kongxiangxin/pine/tree/master/auto-closeable

随机推荐

  1. 如何通过 Freemark 优雅地生成那些花里胡哨的复杂样式 Excel 文件?

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 高级架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...

  2. efcore mysql数据库codefirst生成

    添加引用 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Tools Pomelo.EntityFrameworkCore.My ...

  3. MTSC2019大会日程重磅发布,腾讯WeTest独家Topic大揭秘!

    WeTest 导读 中国移动互联网测试开发大会 Mobile Testing Summit China(简称 MTSC)是由国内最大的移动测试技术社区 TesterHome 发起的软件测试行业技术会议 ...

  4. Ext学习之路——Ext.define

    Ext.define('My.awesome.Class', { someProperty: 'something', someMethod: function() { alert(s + this. ...

  5. 把本地项目提交到GIT上

    1.init之前 1.1 新建.gitignore文件 在提交之前.gitignore文件会把文件里面包含的内容都忽略掉 node_modules // webstorm里面的配置,别人不一定用 .i ...

  6. 英语LIGNALOO沉香lignaloo单词

    沉香lignaloo,是瑞香科.沉香属的一种乔木,高5-15米.树皮暗灰色,几平滑,纤维坚韧:小枝圆柱形,具绉纹,幼时被疏柔毛,后逐渐脱落,无毛或近无毛.产于中国广东.海南.广西.福建等地.喜生于低海 ...

  7. 深度解析.NetFrameWork/CLR/C# 以及C#6/C#7新语法

    一:什么是.NetFrameWork/ CLR / C# 1:.NetFramework即架构,它是一个语言开发软件,提供了软件开发的框架,使开发更具工程性.简便性和稳定性,这个框架主要是针对于c#语 ...

  8. 【DB_MySQL】MySQL日志分析

    MySQL数据库常见的日志有:错误日志(log_error).慢查询日志(slow_query_log).二进制日志(bin_log).通用日志(general_log) 开启慢查询日志并分析 开启慢 ...

  9. [TCP/IP] TCP如何实现流量控制和拥塞控制

    流量控制:数据的传送与接收过程当中很可能出现收方来不及接收的情况,这时就需要对发方进行控制,以免数据丢失.流量控制用于防止在端口阻塞的情况下丢帧,这种方法是当发送或接收缓冲区开始溢出时通过将阻塞信号发 ...

  10. 007-OpenStack-启动实例

    OpenStack-启动实例 [基于此文章的环境]点我快速打开文章 1.控制节点操作(controller) [官方文档]点我快速打开文章 1. 创建网络 neutron net-create --s ...