處理異常的最佳做法

來源:互聯網
上載者:User
計良好的錯誤處理代碼塊集可使程式更可靠並且不容易崩潰,因為應用程式可處理這樣的錯誤。下表包含有關處理異常的最佳做法的建議:

  • 知道何時設定 Try/Catch 塊。例如,可以以編程方式檢查可能發生的條件,而不使用異常處理。在其他情況下,使用異常處理捕捉錯誤條件是適當的。

    下面的樣本使用 if 語句檢查串連是否關閉。如果串連未關閉,可以使用此方法而不是引發異常。

    Visual Basic 複製代碼
    If conn.State <> ConnectionState.Closed Then      conn.Close()   End If
    C# 複製代碼
    if(conn.State != ConnectionState.Closed)      conn.Close();

    在下面的樣本中,如果串連未關閉,則引發異常。

    Visual Basic 複製代碼
    Try      conn.Close()   Catch ex As InvalidOperationException      'Do something with the error or ignore it.   End Try
    C# 複製代碼
    try {     conn.Close();   }   catch(InvalidOperationException ex) {     //Do something with the error or ignore it.   }

    所選擇的方法依賴於預計事件發生的頻率。如果事件確實是異常的並且是一個錯誤(如意外的檔案尾),則使用異常處理比較好,因為正常情況下執行的代碼更少。如果事件是例行發生的,使用編程方法檢查錯誤比較好。在此情況下,如果發生異常,將需要更長的時間處理。

  • 在可潛在產生異常的代碼周圍使用 Try/Finally 塊,並將 Catch 語句集中在一個位置。以這種方式,Try 語句產生異常,Finally 語句關閉或釋放資源,而 Catch 語句從中心位置處理異常。

  • 始終按從最特定到最不特定的順序對 Catch 塊中的異常排序。此方法在將特定異常傳遞給更常規的 Catch 塊之前處理該異常。

  • 以“Exception”這個詞作為異常類名的結尾。例如:

    Visual Basic 複製代碼
    Public Class EmployeeListNotFoundException    Inherits Exception
    C# 複製代碼
    public class MyFileNotFoundException : Exception {}
  • 當建立使用者定義的異常時,必須確保異常的中繼資料對遠程執行的代碼可用,包括當異常跨應用程式定義域發生時。例如,假設應用程式定義域 A 建立應用程式定義域 B,後者執行引發異常代碼。應用程式定義域 A 若想正確捕獲和處理異常,它必須能夠找到包含應用程式定義域 B 所引發的異常的程式集。如果包含應用程式定義域 B 引發的異常的程式集位於應用程式定義域 B 的應用程式基底目錄下,而不是位於應用程式定義域 A 的應用程式基底目錄下,則應用程式定義域 A 將無法找到異常,公用語言運行庫將引發 FileNotFoundException。為避免此情況,可以兩種方式部署套件含異常資訊的程式集:

    • 將程式集放在兩個應用程式定義域共用的公用應用程式基底中

      - 或 -

    • 如果兩個應用程式定義域不共用一個公用應用程式基底,則用強式名稱給包含異常資訊的程式集簽名並將其部署到全域組件快取中。

  • 在 C# 和 C++ 中建立您自己的異常類時,至少使用三個公用建構函式。有關樣本,請參見如何:建立使用者定義的異常。

  • 在大多數情況下,使用預定義的異常類型。僅為編程方案定義新異常類型。引入新異常類,使程式員能夠根據異常類在代碼中採取不同的操作。

  • 對於大多數應用程式,從 Exception 類派生自訂異常。最初要求自訂異常應該從 ApplicationException 類派生;但是在實踐中並未發現這樣有很大意義。

  • 在每個異常中都包含一個本地化描述字串。當使用者看到錯誤資訊時,該資訊從引發的異常的描述字串派生,而不是從異常類派生。

  • 使用文法上正確的錯誤資訊(包括結束標點符號)。在異常的描述字串中,每個句子都應以句號結尾。

  • 為編程訪問提供 Exception 屬性。僅當存在附加資訊有用的編程方案時,才在異常中包含附加資訊(不包括描述字串)。

  • 對非常常見的錯誤情況返回 null。例如,如果沒找到檔案,Open 將返回 null;但如果檔案被鎖定,則引發異常。

  • 類的設計應使在正常使用中從不引發異常。例如,FileStream 類公開另一種確定是否已到達檔案末尾的方法。這避免了在讀取超過檔案尾時引發的異常。下面的樣本顯示如何讀到檔案尾。

    Visual Basic 複製代碼
    Class FileRead    Public Sub Open(ByVal fileToRead As FileStream)        ' This If statement is optional        ' as it is very unlikely that        ' the stream would ever be null        If IsDBNull(fileToRead) Then            Throw New System.ArgumentNullException()        End If        Dim b As Integer        ' Set the stream position to the beginning of the file.        fileToRead.Seek(0, SeekOrigin.Begin)        ' Read each byte to the end of the file.        For i As Integer = 0 To fileToRead.Length            b = fileToRead.ReadByte()            Console.Write(b.ToString())            ' Or do something else with the byte.        Next    End SubEnd Classclass FileRead {    public void Open(FileStream fileToRead)     {        // This if statement is optional        // as it is very unlikely that        // the stream would ever be null.        if (fileToRead == null)        {            throw new System.ArgumentNullException();        }        int b;        // Set the stream position to the beginning of the file.        fileToRead.Seek(0, SeekOrigin.Begin);        // Read each byte to the end of the file.        for (int i = 0; i < fileToRead.Length; i++)        {            b = fileToRead.ReadByte();            Console.Write(b.ToString());            // Or do something else with the byte.        }    }}
  • 如果根據對象的目前狀態,屬性集或方法調用不適當,則引發 InvalidOperationException。

  • 如果傳遞的參數無效,則引發 ArgumentException 或從 ArgumentException 派生的類。

  • 堆疊追蹤從引發異常的語句開始,到捕捉異常的 Catch 語句結束。當決定在何處放置 Throw 語句時需考慮這一點。

  • 使用異常產生器方法。類從其實現中的不同位置引發同一異常是常見的情況。為避免過多的代碼,應使用協助器方法建立異常並將其返回。例如:

    Visual Basic 複製代碼
    Class File   Private fileName As String      Public Function Read(bytes As Integer) As Byte()      If Not ReadFile(handle, bytes) Then         Throw NewFileIOException()      End If   End Function 'Read      Function NewFileIOException() As FileException      Dim description As String = __unknown ' Build localized string, including fileName.      Return New FileException(description) '   End Function 'NewFileIOExceptionEnd Class 'File
    C# 複製代碼
    class File {    string fileName;    public byte[] Read(int bytes) {        if (!ReadFile(handle, bytes))            throw NewFileIOException();    }    FileException NewFileIOException() {        string description = // Build localized string, including fileName.        return new FileException(description);     }}

    或者,使用異常的建構函式產生異常。這更適合全域異常類,例如 ArgumentException。

  • 引發異常,而不是返回錯誤碼或 HRESULT。

  • 引發異常時清理中間結果。當異常從方法引發時,調用方應該能夠假定沒有副作用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.