CA1064:例外狀況必須是公用

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

原因

非公用例外狀況直接衍生自 ExceptionSystemExceptionApplicationException

檔案描述

內部例外狀況只會顯示在自己的內部範圍內。 當例外狀況超出內部範圍後,只能使用基本例外狀況來攔截例外狀況。 如果內部例外狀況是繼承自 ExceptionSystemExceptionApplicationException,外部程式碼就沒有足夠的資訊可以知道應該如何處理此例外狀況。

但是,如果程式代碼具有稍後用來作為內部例外狀況基底的公用例外狀況,則假設進一步輸出的程式代碼能夠以智慧型手機方式執行基底例外狀況。 公用例外狀況會比 、 SystemExceptionApplicationException所提供的Exception資訊還多。

如何修正違規

將例外狀況公開,或從不是 ExceptionSystemExceptionApplicationException的公用例外狀況衍生內部例外狀況。

隱藏警告的時機

如果您確定所有情況下都會在自己的內部範圍內攔截私人例外狀況,請隱藏此規則中的訊息。

隱藏警告

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

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

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

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

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

範例

此規則會在第一個範例方法 FirstCustomException 上引發,因為例外狀況類別直接衍生自 Exception,而且是內部的。 規則不會在 SecondCustomException 類別上引發,因為雖然 類別也直接衍生自 Exception,但類別會宣告為 public。 第三個類別也不會引發規則,因為它不會直接衍生自 System.ExceptionSystem.SystemExceptionSystem.ApplicationException

// Violates this rule
[Serializable]
internal class FirstCustomException : Exception
{
    internal FirstCustomException()
    {
    }

    internal FirstCustomException(string message)
        : base(message)
    {
    }

    internal FirstCustomException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    protected FirstCustomException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}

// Does not violate this rule because
// SecondCustomException is public
[Serializable]
public class SecondCustomException : Exception
{
    public SecondCustomException()
    {
    }

    public SecondCustomException(string message)
        : base(message)
    {

    }

    public SecondCustomException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    protected SecondCustomException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}

// Does not violate this rule because
// ThirdCustomException it does not derive directly from
// Exception, SystemException, or ApplicationException
[Serializable]
internal class ThirdCustomException : SecondCustomException
{
    internal ThirdCustomException()
    {
    }

    internal ThirdCustomException(string message)
        : base(message)
    {
    }

    internal ThirdCustomException(string message, Exception innerException)
        : base(message, innerException)
    {
    }


    protected ThirdCustomException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}