在C#中如何定义我自己的异常? [英] In C# how do I define my own Exceptions?

查看:84
本文介绍了在C#中如何定义我自己的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中如何定义自己的异常?

In C# how do I define my own Exceptions?

推荐答案

创建自己的异常的指导你的课程应该从异常继承)

Guidelines for creating your own exception (next to the fact that your class should inherit from exception)


  • 确保课程是可序列化的,通过添加 [Serializable] code>属性

  • 提供异常使用的常见构造函数:

  • make sure the class is serializable, by adding the [Serializable] attribute
  • provide the common constructors that are used by exceptions:

MyException ();

MyException (string message);

MyException (string message, Exception innerException);


所以,理想情况下,你的自定义异常应该至少看起来像这样:

So, ideally, your custom Exception should look at least like this:

[Serializable]
public class MyException : Exception
{
    public MyException ()
    {}

    public MyException (string message) 
        : base(message)
    {}

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

关于你是否应该继承例外 ApplicationException
FxCop有一个规则说你应该避免继承 ApplicationException

About the fact whether you should inherit from Exception or ApplicationException: FxCop has a rule which says you should avoid inheriting from ApplicationException:

CA1058:Microsoft.Design:

更改
MyException的基本类型,以便
不再扩展
' ApplicationException的。此基础
异常类型不为框架
类提供任何
附加值。扩展'System.Exception'或
一个现有的未密封的异常类型
。不要创建一个新的例外
基类型,除非在
异常的整个类中启用
catch处理程序的特定
值。

CA1058 : Microsoft.Design :
Change the base type of 'MyException' so that it no longer extends 'ApplicationException'. This base exception type does not provide any additional value for framework classes. Extend 'System.Exception' or an existing unsealed exception type instead. Do not create a new exception base type unless there is specific value in enabling the creation of a catch handler for an entire class of exceptions.

请参阅 MSDN上的页面关于此规则。

这篇关于在C#中如何定义我自己的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆