Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >CA1064:异常应该是公共的

CA1064:异常应该是公共的

作者头像
呆呆
发布于 2022-02-22 12:57:09
发布于 2022-02-22 12:57:09
28400
代码可运行
举报
文章被收录于专栏:centosDaicentosDai
运行总次数:0
代码可运行

规则 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
代码运行次数:0
运行
AI代码解释
复制
// 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 删除。

评论
登录后参与评论
暂无评论
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验