分享方式:


CA1032:必須實作標準例外狀況建構函式

屬性
規則識別碼 CA1032
標題 必須實作標準例外狀況建構函式
類別 設計
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

類型會 System.Exception 擴充,但不會宣告所有必要的建構函式。

檔案描述

例外狀況類型必須實作下列三個公用建構函式:

  • public NewException()

  • public NewException(string)

  • public NewException(string, Exception)

無法提供整組的建構函式會導致難以正確地處理例外狀況。 例如,具有簽章 NewException(string, Exception) 的建構函式可用來建立其他例外狀況所造成的例外狀況。 如果沒有這個建構函式,您就無法建立並擲回包含內部(巢狀)例外狀況的自定義例外狀況實例,這是 Managed 程式代碼在這類情況下應該執行的動作。

如需詳細資訊,請參閱 CA2229:實作串行化建構函式

如何修正違規

若要修正此規則的違規,請將遺漏的建構函式新增至例外狀況,並確定它們具有正確的輔助功能。

隱藏警告的時機

當違規是由公用建構函式使用不同的存取層級所造成時,隱藏此規則的警告是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA1032
// The code that's violating the rule is on this line.
#pragma warning restore CA1032

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

[*.{cs,vb}]
dotnet_diagnostic.CA1032.severity = none

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

範例

下列範例包含違反此規則的例外狀況類型,以及正確實作的例外狀況類型。

// Violates rule ImplementStandardExceptionConstructors.
public class BadException : Exception
{
    public BadException()
    {
        // Add any type-specific logic, and supply the default message.
    }
}

[Serializable()]
public class GoodException : Exception
{
    public GoodException()
    {
        // Add any type-specific logic, and supply the default message.
    }

    public GoodException(string message) : base(message)
    {
        // Add any type-specific logic.
    }

    public GoodException(string message, Exception innerException) :
       base(message, innerException)
    {
        // Add any type-specific logic for inner exceptions.
    }
}

另請參閱

CA2229:必須實作序列化建構函式