簡體   English   中英

在Java中,在引發異常的方法中關閉變量的正確方法是什么?

[英]In Java, what is the right way to close variables in a method that throws exceptions?

在Java中,我經常在finally塊中關閉變量,如下所示:

public void someMethod(){
  InputStream inStream = null;
  PreparedStatement pStatement = null;

  try{ do something here }
  catch(Exception ex){ do something here }
  finally{
    try{ if (inStream != null) inStream.close(); } catch(Exception ex){/* do nothing */}
    try{ if (pStatement != null) pStatement.close(); } catch(Exception ex){/* do nothing */}
  }
}

我想知道,如果該方法說它引發了異常,是否有一個像“最終”這樣的地方可以關閉該方法的變量? 例如:

public void anotherMethod() throws SQLException {
  // This method doesn't need a try/catch because the method throws an exception.
  InputStream inStream = null;
  PreparedStatement pStatement = null;

  // Where can I ensure these variables are closed?
  // I would prefer not to have them be global variables.
}

正確的方法實際上是使用Java 7中引入的try-with-resources構造。

public void anotherMethod() throws SQLException {
    try (PreparedStatement st = connection.prepareStatement(...)) {
        // do things with st
    }
}

這樣可以確保在try塊中發生的任何事情(成功執行或以異常結束)都會關閉資源。 您無需添加catch部分,因為該方法會引發SQLException ,更重要的是,您無需添加finally子句:保證所有已打開的資源在該語句之后都將被關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM