前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >CA1064:异常应该是公共的

CA1064:异常应该是公共的

作者头像
呆呆
发布2022-02-22 20:57:09
2410
发布2022-02-22 20:57:09
举报
文章被收录于专栏:centosDaicentosDai

规则 ID

CA1064

类别

设计

修复是中断修复还是非中断修复

非中断

原因

非公共异常直接派生自 Exception、SystemException 或 ApplicationException。

规则说明

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

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

如何解决冲突

使异常成为公共异常,或从不是 Exception、SystemException 或 ApplicationException 的公共异常派生内部异常。

何时禁止显示警告

如果确定在所有情况下私有异常都将在其自己的内部范围内被捕获,则禁止显示此规则的消息。

示例

此规则在第一个示例方法 FirstCustomException 上触发,因为 exception 类直接派生自 Exception ,并且是内部类。 此规则不会在 SecondCustomException 类上触发,尽管该类也直接派生自 Exception,但该类声明为公共类。 第三个类也不会触发该规则,因为它并非直接派生自 System.Exception、System.SystemException 或 System.ApplicationException。

代码语言:javascript
复制
// 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)
    {
    }
}

本文系外文翻译,前往查看

如有侵权,请联系?cloudcommunity@tencent.com?删除。

本文系外文翻译前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com