2015-07-21 35 views
1

代碼:Java嘗試抓住,最後。如果發生異常,最終還是會保留參考?

try { 

      dbConnection = jdbcTemplate.getDataSource().getConnection(); 
      callableStatement = dbConnection.prepareCall(getDBUSERCursorSql); 
     } 
    catch (SQLException e) { 
     LOGGER.error("Error occured", e); 
    } 
    finally 
    { 
     if (dbConnection != null && !dbConnection.isClosed()) { 
        dbConnection.close(); 
     } 
    } 

因此,如果在線路的CallableStatement = dbConnection.prepareCall(getDBUSERCursorSql)發生異常;並且catch塊執行後,將會在finally塊中仍然存在對dbConnection的引用嗎? Fortify說不,但我不確定增強是否正確。

+0

nope,因爲異常將在賦值之前拋出 – JohnnyAW

+0

我認爲只要'dbConnection'被定義在'try catch'之外鎖定它仍然存在。試一試? :) –

+0

@ EM-Creations這個問題不是關於變量是否可用,它關於對dbConnection的引用:) – JohnnyAW

回答

2

如果dbConnection變量在try塊之前聲明,它將在finally塊中可用。現在,它的值是否爲null取決於try塊的代碼。如果唯一可以拋出異常的代碼是dbConnection = jdbcTemplate.getDataSource().getConnection();行,那麼如果該行引發異常,則該行可能爲空。

例如,下面的代碼是有效的:

Connection dbConnection = null; 
try { 
    dbConnection = jdbcTemplate.getDataSource().getConnection(); 
    callableStatement = dbConnection.prepareCall(getDBUSERCursorSql); 
} 
catch (SQLException e) { 
    LOGGER.error("Error occured", e); 
} 
finally 
{ 
    if (dbConnection != null && !dbConnection.isClosed()) { 
     dbConnection.close(); 
    } 
} 

如果,另一方面,你聲明dbConnection try塊內,你的代碼將無法通過編譯。

編輯:

如果callableStatement = dbConnection.prepareCall(getDBUSERCursorSql);拋出異常時,最終塊將必須由dbConnection稱爲連接實例的引用,並且將能夠關閉連接。

+0

是連接「dbConnection = null;」在嘗試之前聲明 –

+0

問題是關於dbConnection的引用,而不是關於變量本身 – JohnnyAW

+0

@JohnnyAW'dbConnection'本身就是可以引用的東西。這就是問題所在。 –

1

The finally Block

的finally塊總是執行try塊退出時。即使發生意外的 異常,此 可確保執行finally塊。

所以,是的。如果在前面的try塊內沒有丟失其範圍,則對dbConnection的引用仍然存在於finally塊中。

1

謝謝你們。是的,最後有參考。我想我應該試圖通過自己在一審

public static void main(String[] args) { 
     String msg ="StringIsNotNull"; 
     printThis(msg); 

    } 

    private static void printThis(String msg){ 
     try{ 
      System.out.println(msg); 
      throw new Exception(); 
     } 
     catch (Exception e){ 
      System.out.println(e); 
     } 
     finally{ 
      System.out.println(msg); 
      msg=null; 
     } 

    } 

下面當我跑到上面,我得到了以下

StringIsNotNull

java.lang.Exception的

StringIsNotNull