In C# how do I define my own Exceptions?

前端 未结 8 2055
北荒
北荒 2020-12-07 23:51

In C# how do I define my own Exceptions?

8条回答
  •  [愿得一人]
    2020-12-08 00:30

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

    • 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)
        {}    
    }
    

    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 :
    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.

    See the page on MSDN regarding this rule.

提交回复
热议问题