实现了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. maven聚合项目以及使用dubbo远程服务调用debug操作。

    1.maven聚合项目以及使用dubbo远程服务调用debug操作. 然后操作如下所示: 然后如下所示: 启动断点所在的包的服务.以debug的形式启动. 断点进来的效果如下所示: 接下来请继续你的表 ...

  2. 2019-11-25-如何在国内发布-UWP-应用

    原文:2019-11-25-如何在国内发布-UWP-应用 title author date CreateTime categories 如何在国内发布 UWP 应用 lindexi 2019-11- ...

  3. datatable转layui表格v2[分页and带模板]【偏实例】

    本项目由普通mvc+webapi接口构成.按执行顺序,代码如下:主控制器:public ActionResult Index(int id=0) { ViewData["myid" ...

  4. C#下的时间测试(用于计算方法执行时间)

    public class Timing { private TimeSpan m_StartTime; private TimeSpan duringTime; public Timing() //构 ...

  5. open*** 搭建

    pptp 互联网上服务商给拦截.不稳定. opevpn 1.为了保证OpenVPN的安装,需要使用easy-rsa秘钥生成工具生成证书 [root@m01 ~]# yum install easy-r ...

  6. 腾讯WeTest加入智慧零售“倍增计划”,引领微信小程序质量优化

    WeTest 导读 在2019腾讯全球数字生态大会零售分论坛上,腾讯正式面向全行业合作伙伴发布倍增计划,通过咨询.培训.竞赛三步走,帮助零售商户解决前端触点融通的问题,推动微信生意大盘阶梯式上涨. 倍 ...

  7. android studio学习----gradle多渠道打包

    由于国内Android市场众多渠道,为了统计每个渠道的下载及其它数据统计,就需要我们针对每个渠道单独打包,如果让你打几十个市场的包岂不烦死了,不过有了Gradle,这再也不是事了. 友盟多渠道打包 废 ...

  8. MQTT实战2 - 使用MQTTnet实现mqtt通信

    MQTT实战1 - 使用Apache Apollo代理服务器实现mqtt通信 MQTT实战2 - 使用MQTTnet实现mqtt通信 源码下载 -> 提取码  QQ:505645074 MQTT ...

  9. jQuery基础的动画里面的回调函数

    <style> *{margin:0; padding:0;} #target{ border-radius:10px; background:#eee; } .fade{/*动画起始状态 ...

  10. php session的理解【转】

    目录 1.什么是session? 2.Session常见函数及用法? ● 如何删除session? ● SESSION安全: Session跨页传递问题: 1.什么是session?   Sessio ...