2015-07-21 65 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