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.pswp.cn/news/374817.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374817.shtml
英文地址,請注明出處:http://en.pswp.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/…