#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++)
                Console.WriteLine("Woof");
        }

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

    [Serializable]
    public class Dog

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – July 17, 2013 (#1,586) | Alvin Ashcraft's Morning Dew

Leave a comment