0

In the following code snippet,

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

what happens when an exception occurs in the finally block while executing stmt.close();. Is there a better way to handle these kind of problems?

rajesh
  • 179
  • 1
  • 3
  • 16
  • 2
    You would just log it if it is not serious or rethrow if it needs to be handled. – Vikdor Oct 05 '12 at 06:29
  • Have a look at the following post : http://stackoverflow.com/questions/481446/throws-exception-in-finally-blocks – ranjit Oct 05 '12 at 06:34
  • When you are in a finally, you are simply relasing resources. An exception could be already happen or not. So exception in finally are "pointless"... Case1: You got exception, so if if you cannot close a statement, it will not be a big surprise. Case2: you already committed no error but you cannot close statement: no a big issue, you aready have your work saved, etc – daitangio Oct 05 '12 at 07:02

4 Answers4

3

sometimes connections is not open because of some exception but finally block close that connection. To avoid this Exception check out following code.

    try{ 
      Statement stmt = conect.getConnection();
      stmt.executeUpdate(query);
    }catch(SQLException e){ 
      //handle exception
    }finally{
      try{ 
       if(stmt != null){
         stmt.close(); 
       }
    } 
      catch(SQLException ignore){}
    }
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
007
  • 161
  • 1
  • 3
  • 8
1
   finally 
    {
          if( stmt != null ) {
            try {
              stmt.close();
            }
            catch(SQLException ex ) {
              ex.printStackTrace();
            }
          }
    }
Raj Adroit
  • 3,828
  • 5
  • 31
  • 44
1

Problems which might occur is that a statement isn't closed and then you will get an error when trying to reuse it.

try:

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){}  
   }
macken88
  • 125
  • 11
0

Usually when an exception occur we wrap it over our User defined exception and throw.

Similarly u need to throw ur own exception, when an exception occurs in finally also.

try {

  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");
  }
}
Munesh
  • 1,509
  • 3
  • 20
  • 46