通过


CA1064: 异常应该是公开的

属性
规则 ID CA1064
标题 异常应该是公共的
类别 设计
修复会引起中断还是不会引起中断 非中断
在 .NET 10 中默认启用
适用的语言 C# 和 Visual Basic

原因

非公共异常直接派生自 ExceptionSystemExceptionApplicationException

规则说明

内部异常仅在其自己的内部范围内可见。 当异常超出内部范围后,只能使用基异常来捕获该异常。 如果内部异常继承自 ExceptionSystemExceptionApplicationException,则外部代码将没有足够的信息来了解如何处理该异常。

但是,如果代码有一个公共异常,稍后会用作内部异常的基异常,则有理由认为后续代码将能够对该基异常进行智能化操作。 该公共异常将会比 ExceptionSystemExceptionApplicationException 提供更多的信息。

如何解决违规

将异常公开,或从某种公共异常(而非 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 类直接派生自 Exception ,并且是内部类。 此规则不会在 SecondCustomException 类上触发,尽管该类也直接派生自 Exception,但该类声明为公共类。 第三个类也不会触发该规则,因为它并非直接派生自 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)
    {
    }
}