0

在以下代码片段中,

    try
    { 
      Statement stmt = conect.getConnection();
      stmt.executeUpdate(query);
    }
    catch(SQLException e)
    { 
      //handle exception
    }
    finally
    {
      try{ stmt.close(); } 
      catch(SQLException ignore){}
    }

当执行 stmt.close(); 时 finally 块中发生异常时会发生什么。有没有更好的方法来处理这类问题?

4

4 回答 4

3

有时连接由于某些异常而未打开,但最终阻止关闭该连接。为避免此异常,请查看以下代码。

    try{ 
      Statement stmt = conect.getConnection();
      stmt.executeUpdate(query);
    }catch(SQLException e){ 
      //handle exception
    }finally{
      try{ 
       if(stmt != null){
         stmt.close(); 
       }
    } 
      catch(SQLException ignore){}
    }
于 2012-10-05T06:37:04.153 回答
1
   finally 
    {
          if( stmt != null ) {
            try {
              stmt.close();
            }
            catch(SQLException ex ) {
              ex.printStackTrace();
            }
          }
    }
于 2012-10-05T06:33:59.060 回答
1

可能出现的问题是语句没有关闭,然后在尝试重用它时会出错。

尝试:

Statement stmt = null;
try {
        stmt = conect.getConnection();
        stmt.executeUpdate(query);
    }    
 catch(SQLException e) {       
          //handle exception  
   }    
 finally   
  {     
     try{ if(stmt!=null)stmt.close(); }    
     catch(SQLException ignore){}  
   }
于 2012-10-05T06:37:08.273 回答
0

通常当发生异常时,我们将其包装在用户定义的异常上并抛出。

同样,当 finally 发生异常时,您需要抛出自己的异常。

尝试 {

  Statement stmt = conect.getConnection();
  stmt.executeUpdate(query);
}
catch(SQLException e)
{ 
  //handle exception 
   throw MyOwnException(e,"My message");
}
finally
{
  try{ stmt.close(); } 
  catch(SQLException ignore)
  {
      throw MyOwnException(ignore,"My message");
  }
}
于 2012-10-05T09:02:14.833 回答