#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;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #896 – Custom Exceptions Should Be Marked as Serializable

  1. Dirk Strauss says:

    Excellent tip! Thanks Sean. I think I have some work to do in one of my classes that implements custom exceptions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: