#896 – Custom Exceptions Should Be Marked as Serializable

Whenever you create a custom exception type, your exception type should always support serialization.  You do this using the Serializable attribute.  Exceptions should be serializable so that they can automatically be marshalled across application domains or threads.

At a minimum, you should mark your custom exception as serializable and implement the four basic constructors shown below.  (This example shows a custom exception type that has no custom data).

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

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

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

        protected DogBarkException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }

Note: For access to the SerializationInfo and StreamingContext types, you’ll need the following using statement:

using System.Runtime.Serialization;