#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
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 #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 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: