#888 – Objects Added to Exception’s Data Dictionary Must Be Serializable

You can use an Exception object’s Data property to add useful data to an exception that you are throwing.

When you add an entry to this dictionary, you need to make sure that the object being stored is serializable.  That is, it’s state can be completely captured and later used to reconstitute the object.

In the example below, we add a Dog instance to the Data property’s dictionary.  If the Dog class is not serializable, we’ll get an ArgumentException on the Add call.

        // Dog.Bark
        public void Bark(int numTimes)
            if (numTimes > 12)
                Exception xx = new Exception("Too much barking");
                xx.Data.Add("Dog", this);
                throw xx;

            for (int i = 0; i < numTimes; i++)

We can fix this problem by marking the Dog class as serializable.

    public class Dog