Java 7:尝试资源

本文研究try-with-resources语句的用法。 这是一个声明一个或多个资源的try语句。 资源是一个对象,程序完成后必须将其关闭。

try-with-resources语句可确保在语句末尾关闭每个资源。 任何实现java.lang.AutoCloseable或java.io.Closeable接口的对象都可以用作资源。

在尝试使用资源 (在Java 7之前)处理SQL语句或ResultSet或Connection对象或其他IO对象之前,必须显式关闭资源。 所以一个人会写类似:

try{//Create a resource- R
} catch(SomeException e){//Handle the exception
} finally{//if resource R is not null thentry{//close the resource}catch(SomeOtherException ex){}
}

我们必须显式关闭资源,从而添加更多代码行。 在极少数情况下,开发人员会忘记关闭资源。 因此,为了克服这些问题和其他问题,Java 7中引入了try-with-resources 。

让我们看一个示例,说明如何在Java 7之前的版本中使用try..catch…。让我创建2个自定义异常-ExceptionA和ExceptionB。 这些将在整个示例中使用。

public class ExceptionA extends Exception{public ExceptionA(String message){super(message);}
}
public class ExceptionB extends Exception{public ExceptionB(String message){super(message);}
}

让我们创建一些资源,例如OldResource,它有两种方法– doSomeWork():完成一些工作,close():完成关闭。 请注意,这描述了通用资源的使用-做一些工作,然后关闭资源。 现在,每个操作doSomeWork和close都会引发异常。

public class OldResource{public void doSomeWork(String work) throws ExceptionA{System.out.println("Doing: "+work);throw new ExceptionA("Exception occured while doing work");}public void close() throws ExceptionB{System.out.println("Closing the resource");throw new ExceptionB("Exception occured while closing");}
}

让我们在示例程序中使用此资源:

public class OldTry {public static void main(String[] args) {OldResource res = null;try {res = new OldResource();res.doSomeWork("Writing an article");} catch (Exception e) {System.out.println("Exception Message: "+e.getMessage()+" Exception Type: "+e.getClass().getName());} finally{try {res.close();} catch (Exception e) {System.out.println("Exception Message: "+e.getMessage()+" Exception Type: "+e.getClass().getName());}}}
}

输出:

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的try-with-resource结构实现相同的程序。 为此,我们需要一个新资源– NewResource。 在Java 7中,新接口为java.lang.AutoCloseable 。 那些需要关闭的资源将实现此接口。 所有较旧的IO API,套接字API等都实现了Closeable接口-这意味着可以关闭这些资源。 使用Java 7, java.io.Closeable实现AutoCloseable 。 因此,一切正常,而不会破坏任何现有代码。

下面的NewResource代码:

public class NewResource implements AutoCloseable{String closingMessage;public NewResource(String closingMessage) {this.closingMessage = closingMessage;}public void doSomeWork(String work) throws ExceptionA{System.out.println(work);throw new ExceptionA("Exception thrown while doing some work");}public void close() throws ExceptionB{System.out.println(closingMessage);throw new ExceptionB("Exception thrown while closing");}public void doSomeWork(NewResource res) throws ExceptionA{res.doSomeWork("Wow res getting res to do work");}
}

现在,使用try-with-resource在示例程序中使用NewResource:

public class TryWithRes {public static void main(String[] args) {try(NewResource res = new NewResource("Res1 closing")){res.doSomeWork("Listening to podcast");} catch(Exception e){System.out.println("Exception: "+e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());}}
}

输出:

Listening to podcast
Res1 closing
Exception: Exception thrown while doing some work Thrown by: ExceptionA

上面要注意的一件事是,关闭方法抛出的异常被worker方法抛出的异常所抑制。

因此,您可以立即注意到这两种实现之间的差异,一种实现最终使用try ... catch ...,另一种使用try-with-resource。 在上面的示例中,仅一个资源被声明为已使用。 一个人可以在try块中声明和使用多个资源,也可以嵌套这些try-with-resources块。

随之,在java.lang.Throwable类中添加了一些新方法和构造函数,所有这些方法都与抑制与其他异常一起抛出的异常有关。 最好的例子是-try块抛出的ExceptionA会被finally(关闭资源时)抛出的ExceptionB抑制,这是Java 7之前的行为。

但是,对于Java 7,抛出的异常会跟踪它在被捕获/处理的过程中被抑制的异常。 因此,前面提到的示例可以重新陈述如下。 由close方法抛出的ExceptionB被添加到由try块抛出的ExceptionA的抑制异常列表中。

让我用以下示例说明您嵌套的try-with-resources和Suppressed异常。

嵌套的尝试资源

public class TryWithRes {public static void main(String[] args) {try(NewResource res = new NewResource("Res1 closing");NewResource res2 = new NewResource("Res2 closing")){try(NewResource nestedRes = new NewResource("Nestedres closing")){nestedRes.doSomeWork(res2);}} catch(Exception e){System.out.println("Exception: "+e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());}}
}

上面的输出将是:

Wow res getting res to do work
Nestedres closing
Res2 closing
Res1 closing
Exception: Exception thrown while doing some work Thrown by: ExceptionA

注意关闭资源的顺序,最新的优先。 还要注意,抑制了每个close()操作引发的异常。

让我们看看如何检索被抑制的异常:

禁止的异常

public class TryWithRes {public static void main(String[] args) {try(NewResource res = new NewResource("Res1 closing");NewResource res2 = new NewResource("Res2 closing")){try(NewResource nestedRes = new NewResource("Nestedres closing")){nestedRes.doSomeWork(res2);}} catch(Exception e){System.out.println("Exception: "+e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());if (e.getSuppressed() != null){for (Throwable t : e.getSuppressed()){System.out.println(t.getMessage()+" Class: "+t.getClass().getSimpleName());}}}}
}

上面代码的输出:

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

getSuppressed()方法用于检索被抛出的异常阻止的异常。 还向Throwable类添加了新的构造函数,该构造函数可用于启用或禁用异常抑制。 如果禁用,则不会跟踪任何抑制的异常。

参考: Java 7项目硬币: Try -with-resources,以及我们的JCG合作伙伴 Mohamed Sanaulla在Experiences Unlimited Blog 上的示例进行了解释 。

相关文章 :
  • 速览Java 7 MethodHandle及其用法
  • JDK中的设计模式
  • 了解和扩展Java ClassLoader
  • Java内存模型–快速概述和注意事项

翻译自: https://www.javacodegeeks.com/2011/07/java-7-try-with-resources-explained.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/374817.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring学习(19)--- Schema-based AOP(基于配置的AOP实现) --- 配置切面aspect

Spring所有的切面和通知器都必须放在一个<aop:config>内&#xff08;可以配置包含多个<aop:config>元素&#xff09;&#xff0c;每个<aop:config>包含pointcut&#xff0c;advisor和apsect元素。ps&#xff1a;他们必须按照这个顺序进行声明 <aop:pointc…

2021-10-08

word文档&#xff1a;.doc .docx 需求文档、架构文档、接口文档、详设文档一般都是用word编写。 Excel表格&#xff1a;.xls、.xlsx’&#xff0c;.csv 测试用例 PPT幻灯片&#xff1a;.ppt、*.pptx 版本不同 可执行文件&#xff08;windows系统&#xff09;&#xff1a; *.exe…

UITableViewCell 选中的状态小技巧

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {[super setSelected:selected animated:animated]; //cell 没被选中时 隐藏这个 _leftImageViewself.leftImageView.hidden !selected; //选中text变红 不然变灰色self.textLabel.textColor selected ? [UICol…

Spring和AspectJ的领域驱动设计

在JavaCodeGeeks主持的上一篇文章中&#xff0c;我们的JCG合作伙伴 Tomasz Nurkiewicz介绍了使用State设计模式进行领域驱动设计的介绍 。 在该教程的最后&#xff0c;他承认他省略了如何将依赖项&#xff08;DAO&#xff0c;业务服务等&#xff09;注入域对象的过程。 但是&am…

BZOJ 3143 HNOI2013 游走 高斯消元 期望

这道题是我第一次使用高斯消元解决期望类的问题&#xff0c;首发A了&#xff0c;感觉爽爽的.... 不过笔者在做完后发现了一些问题&#xff0c;在原文的后面进行了说明。 中文题目&#xff0c;就不翻大意了&#xff0c;直接给原题&#xff1a; 一个无向连通图&#xff0c;顶点从…

VS2019安全函数scanf_s问题

VS2017、VS2019等安全函数scanf_s问题&#xff1a; scanf()、gets()、fgets()、strcpy()、strcat() 等都是C语言自带的函数&#xff0c;它们都是标准函数&#xff0c;但是它们都有一个缺陷&#xff0c;就是不安全&#xff0c;可能会导致数组溢出或者缓冲区溢出&#xff0c;让黑…

eclipse启动tomcat, http://localhost:8080无法访问的解决方案

问题:&#xff1a; tomcat在eclipse里面能正常启动&#xff0c;但在浏览器中访问http://localhost:8080/不能访问tomcat管理页面&#xff0c;且报404错误。同时其他项目页面也不能访问。访问的时候出现下列页面: 现在关闭eclipse里面的tomcat&#xff0c;在tomcat安装目录下双击…

GWT EJB3 Maven JBoss 5.1集成教程

大家好&#xff0c; 在本文中&#xff0c;我们将演示如何正确集成GWT和EJB3 &#xff0c;以实现示例项目&#xff0c;使用maven进行构建并将其部署在JBoss 5.1应用服务器上。 实际上&#xff0c;您可以轻松地更改maven构建文件中的依赖关系&#xff0c;并将项目部署到您喜欢的…

VS2019注释整段代码

VS2019注释整段代码 1.注释 先CTRLK&#xff0c;然后CTRLC 2.取消注释&#xff1a; 先CTRLK&#xff0c;然后CTRLU 顺便写一下&#xff1a; VS code注释整段代码 Alt Shift A 注释 CodeBlocks&#xff1a; CtrlShiftC注释掉当前行或选中部分&#xff0c; CtrlShiftX解除注释…

linux中的开机和关机命令

与关机、重新启动相关的命令 * 将数据同步写入硬盘中的命令 sync * 惯用的关机命令 shutdown * 重新启动、关机 reboot halt poweroff sync 强制将内存中的数据写入到硬盘当中。因为linux系统中&#xff0c;数据会缓存在内存当中&#xff0c;所以为了保证数据完整保存在硬盘…

如何在不到1ms的延迟内完成100K TPS

马丁汤普森&#xff08;Martin Thompson&#xff09;和迈克尔巴克&#xff08;Michael Barker&#xff09;讨论了通过采用一种新的基础架构和软件方法来构建HPC金融系统&#xff0c;以不到1ms的延迟处理超过100K TPS的问题。 一些技巧包括&#xff1a; 了解平台 建模领域 明…

获取时间C语言-按秒数

两部分&#xff1a; 1.获取秒数 2.获取“年-月-日-时-分-秒” 1.获取秒数 #include<time.h>//包含的头文件int GetTime() {time_t t;t time(NULL);//另一种写法是//time(t);//当time&#xff08;&#xff09;内参数为空时结果直接输出&#xff0c;否则就会存储在参数…

Spring的69个知识点

目录 Spring 概述依赖注入Spring beansSpring注解Spring数据访问Spring面向切面编程&#xff08;AOP&#xff09;Spring MVCSpring 概述 1. 什么是spring? Spring 是个java企业级应用的开源开发框架。Spring主要用来开发Java应用&#xff0c;但是有些扩展是针对构建J2EE平台的…

python 编码问题之终极解决

结合之前遇到的坑以及下面贴的这篇文章&#xff0c; 总结几种python乱码解决方案&#xff0c;如果遇到乱码&#xff0c;不妨尝试一下&#xff1f; 1&#xff0c;必备 #encodingutf-8 2, python编程环境编码 import sys reload(sys) sys.setdefaultencoding(utf8) 3,不知道神马…

GWT 2 Spring 3 JPA 2 Hibernate 3.5教程

本分步指南将介绍如何使用开发一个简单的Web应用程序 Google的网络工具包 &#xff08;GWT&#xff09;用于富客户端&#xff0c;而Spring作为后端服务器端框架。 该示例Web应用程序将提供对数据库执行CRUD&#xff08;创建检索更新删除&#xff09;操作的功能。 对于数据访问层…

洛谷P1014 [NOIP1999 普及组] Cantor 表

现代数学的著名证明之一是 Georg Cantor 证明了有理数是可枚举的。他是用下面这一张表来证明这一命题的&#xff1a; 代码 import java.util.*; public class Main{public static void main(String[] args){//int x1 0;int i 0;Scanner sc new Scanner(System.in);int n s…

3522: [Poi2014]Hotel( 树形dp )

枚举中点x( 即选出的三个点 a , b , c 满足 dist( x , a ) dist( x , b ) dist( x , c ) ) , 然后以 x 为 root 做 dfs , 显然两个位于 x 的同一颗子树内的点是不可能被同时选到的 . 我们对 x 的每一颗子树进行 dfs , 记录下当前子树中的点到 x 距离为 d ( 1 < d < n )…

第一冲刺阶段工作总结02

1.昨天&#xff1a; 实验简单的安卓程序&#xff0c;开始具体的设计软件界面。 2.今天&#xff1a; 继续设计软件页面&#xff0c;由于安卓虚拟机过于迟缓&#xff0c;配置真机&#xff0c;学习如何在真机上运行程序。 3.遇到的困难&#xff1a; 真机配置不知道怎样配置&#x…

JBoss 4.2.x Spring 3 JPA Hibernate教程第2部分

我们将继续有关Spring 3 &#xff0c; Hibernate &#xff0c; JPA和JBoss 4.2.x – 4.3集成的教程 。 最后一步是创建一个Spring服务&#xff0c;以向最终用户公开功能。 我们必须创建一个接口类和相关的实现类。 首先是接口类&#xff1a; package com.mycomp.myproject.se…

洛谷P1035 [NOIP2002 普及组] 级数求和

代码 import java.util.Scanner;public class Main {public static void main(String args[]){Scanner sc new Scanner(System.in);int k sc.nextInt();int n 0;double Sn 0;while(Sn<k){n;Sn Sn 1.0/n;}System.out.println(n);} }这样写while循环体这需要每次加上1/…