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 に答える