2012-10-05 27 views
0

在下面的代碼段中的異常,如何處理在發生最後塊

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

當異常而執行stmt.close發生在最後塊發生了什麼();. 有沒有更好的方法來處理這類問題?

+2

你只記錄它,如果它不嚴重或重新拋出,如果它需要處理。 – Vikdor

+0

看看以下文章:http://stackoverflow.com/questions/481446/throws-exception-in-finally-blocks – ranjit

+0

當你在一個終於,你只是relacent資源。例外可能已經發生或沒有。因此,最後的異常是「毫無意義的」......案例1:你得到了異常,所以如果你不能關閉一個語句,它不會是一個大驚喜。案例2:您已經提交了沒有錯誤,但您無法關閉語句:沒有什麼大問題,您已經保存了您的工作等等 – daitangio

回答

1
finally 
    { 
      if(stmt != null) { 
      try { 
       stmt.close(); 
      } 
      catch(SQLException ex) { 
       ex.printStackTrace(); 
      } 
      } 
    } 
3

有時連接由於某種異常而未打開,但最終阻止關閉該連接。爲了避免這種異常,請查看以下代碼。

try{ 
     Statement stmt = conect.getConnection(); 
     stmt.executeUpdate(query); 
    }catch(SQLException e){ 
     //handle exception 
    }finally{ 
     try{ 
     if(stmt != null){ 
     stmt.close(); 
     } 
    } 
     catch(SQLException ignore){} 
    } 
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){} 
    } 
0

通常,當異常發生時,我們把它包在我們用戶自定義異常,並拋出。

同樣,你需要拋出你自己的異常,當最後還發生異常。

嘗試 {

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"); 
    } 
} 
相關問題