異常處理的常見問題

來源:互聯網
上載者:User

(本文是http://www.xia7.com/Html/bcyy/Java/2006_03_20_10_174.html的梗概)
以下是一段代碼代碼:
    1 OutputStreamWriter out = ...

  2 java.sql.Connection conn = ...

  3 try { // ⑸

  4  Statement stat = conn.createStatement();

  5  ResultSet rs = stat.executeQuery(

  6   "select uid, name from user");

  7  while (rs.next())

  8  {

  9   out.println("ID:" + rs.getString("uid") // ⑹

  10    ",姓名:" + rs.getString("name"));

  11  }

  12  conn.close(); // ⑶

  13  out.close();

  14 }

  15 catch(Exception ex) // ⑵

  16 {

  17  ex.printStackTrace(); //⑴,⑷

  18 }
在上面這段代碼中,出現了初學者經常遇到不適當的異常處理方法。其實,這段代碼也或多或少在我們的系統中出現,只是並沒有意識到有什麼不當。
作者根據這段代碼,總結出六個反例:
1、丟棄異常:R17中,並不對異常進行實質性處理,僅採用printStackTrace(),這在調試期間是可以的,但在調試結束後,就不應該再這樣使用了。處理辦法:1)處理異常,例如修正問題,提醒某人進行處理;2)重新拋出異常;3)轉換異常,通常是轉換到應用級的容易被使用者理解的異常;4)不捕獲異常;
2、不指定具體異常。
3、不釋放資源。
4、不說明異常的詳細資料。
5、過於龐大的try塊,同時捕捉多個異常,卻難以確認異常來源。
6、輸出資料不完整。例如:在迴圈中出現異常,則顯然不能輸出完整的資訊。

改寫後的代碼:
  OutputStreamWriter out = ...

  java.sql.Connection conn = ...

  try {

   Statement stat = conn.createStatement();

   ResultSet rs = stat.executeQuery(

    "select uid, name from user");

   while (rs.next())

   {

    out.println("ID:" + rs.getString("uid") + ",姓名: " + rs.getString("name"));

   }

  }

  catch(SQLException sqlex)

  {

   out.println("警告:資料不完整");

   throw new ApplicationException("讀取資料時出現SQL錯誤", sqlex);

  }

  catch(IOException ioex)

  {

   throw new ApplicationException("寫入資料時出現IO錯誤", ioex);

  }

  finally

  {

   if (conn != null) {

    try {

     conn.close();

    }

    catch(SQLException sqlex2)

    {

     System.err(this.getClass().getName() + ".mymethod - 不能關閉資料庫連接: " + sqlex2.toString());

    }

   }

      if (out != null) {

    try {

     out.close();

    }

    catch(IOException ioex2)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.