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语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java日期加减秒_Java日期——年、
- 下一篇: mysql 前缀索引 语法_PHP 之M