In C# how do I define my own Exceptions?

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

In C# how do I define my own Exceptions?

8条回答
  •  情书的邮戳
    2020-12-08 00:25


    It seems that I've started a bit of an Exception sublcassing battle. Depending on the Microsoft Best Practices guide you follow...you can either inherit from System.Exception or System.ApplicationException. There's a good (but old) blog post that tries to clear up the confusion. I'll keep my example with Exception for now, but you can read the post and chose based on what you need:

    http://weblogs.asp.net/erobillard/archive/2004/05/10/129134.aspx

    There is a battle no more! Thanks to Frederik for pointing out FxCop rule CA1058 which states that your Exceptions should inherit from System.Exception rather than System.ApplicationException:

    CA1058: Types should not extend certain base types


    Define a new class that inherits from Exception (I've included some Constructors...but you don't have to have them):

    using System;
    using System.Runtime.Serialization;
    
    [Serializable]
    public class MyException : Exception
    {
        // Constructors
        public MyException(string message) 
            : base(message) 
        { }
    
        // Ensure Exception is Serializable
        protected MyException(SerializationInfo info, StreamingContext ctxt) 
            : base(info, ctxt)
        { }
    }
    

    And elsewhere in your code to throw:

    throw new MyException("My message here!");
    

    EDIT

    Updated with changes to ensure a Serializable Exception. Details can be found here:

    Winterdom Blog Archive - Make Exception Classes Serializable

    Pay close attention to the section about steps that need to be taken if you add custom Properties to your Exception class.

    Thanks to Igor for calling me on it!

提交回复
热议问题