【问题标题】:how to handle an exception occured in finally block如何处理 finally 块中发生的异常
【发布时间】:2012-09-26 06:46:13
【问题描述】:

在下面的代码sn-p中,

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

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

【问题讨论】:

  • 不严重的就记录一下,需要处理的再扔。
  • 看看下面的帖子:stackoverflow.com/questions/481446/…
  • 当你进入finally时,你只是在释放资源。异常可能已经发生或未发生。所以 finally 中的异常是“没有意义的”...... Case1:你遇到了异常,所以如果你不能关闭一个语句,那也不会是一个很大的惊喜。案例2:你已经没有犯错,但你不能关闭声明:没什么大问题,你已经保存了你的工作,等等

标签: java exception-handling


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
       finally 
        {
              if( stmt != null ) {
                try {
                  stmt.close();
                }
                catch(SQLException ex ) {
                  ex.printStackTrace();
                }
              }
        }
    

    【讨论】:

      【解决方案3】:

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

      尝试:

      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){}  
         }
      

      【讨论】:

        【解决方案4】:

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

        同样,当 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");
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-19
          • 2011-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-05
          • 2015-01-17
          • 2019-03-31
          • 2011-02-24
          相关资源
          最近更新 更多