日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java 有没有with语句_Java中的try-with-resources语句

發布時間:2023/12/4 java 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 有没有with语句_Java中的try-with-resources语句 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在這個Java程序示例中:

package test;

import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.Statement;

public class Test

{

private static void example(){

String url = "jdbc:oracle:thin:@//localhost:7856/xe";

String user = "user";

String password = "pass";

try(Connection con = DriverManager.getConnection(url, user, password);

Statement stmt = con.createStatement()){

throw new OutOfMemoryError("Error");

}catch (SQLException e){

System.err.println("SQLException");

}

}

public static void main(String [] args){

try{

example();

}catch (OutOfMemoryError e){

System.err.println("OutOfMemoryError");

}

// Rest of code here...

}

}

當在靜態方法example()的主體中拋出OutOfMemoryError錯誤時,在終止靜態方法example()之前,Connection“con”和Statement“stmt”會自動關閉,盡管沒有任何捕獲這些的“catch”錯誤,所以在main()的其余代碼中確保這兩個對象是關閉的?

謝謝.

解決方法:

是; try-with-resources構造總是關閉資源,即使它是一個未經檢查的throwable(如OutOfMemoryError).

這在JLS 14.20.3中指定,它以一個非常通用的語句開始,即資源“自動關閉”,但隨后會進入資源關閉時的各種示例.基本上,任何非空資源總是被關閉,就好像close已經在為一個資源創建的try-finally的finally子句中.即使在try中有多個資源,也就是這種情況(例如,“關閉一個資源時的異常不會阻止關閉其他資源”).

簡單的類來演示它:

public class Twr {

private static class TwrCloseable implements AutoCloseable {

private final String id;

TwrCloseable(String id) {

this.id = id;

}

@Override

public void close() {

System.out.println("closing " + id);

}

}

public static void main(String[] args) {

try (TwrCloseable closeable1 = new TwrCloseable("first");

TwrCloseable closeable2 = new TwrCloseable("second")) {

throw new OutOfMemoryError();

}

}

}

輸出:

closing second

closing first

Exception in thread "main" java.lang.OutOfMemoryError

at Twr.main(Twr.java:19)

請注意,它們以相反的順序關閉; “第二個”在“第一個”之前關閉.在您的示例中,這意味著Statement在Connection之前關閉,這正是您想要的.

標簽:java,try-with-resources

來源: https://codeday.me/bug/20190830/1770761.html

總結

以上是生活随笔為你收集整理的java 有没有with语句_Java中的try-with-resources语句的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。