#887 – Report Additional Data when You Throw an Exception

You can use the Data property of an Exception object to store some additional data that is meant to help the caller to better understand the context in which the exception occurred.

The Data property refers to a dictionary of keyword/value pairs.  You can add your own keyword/value pairs after you create the Exception object and before you throw the exception.

Both the key and the value can be any object, but you’ll most often use a string as the keyword.  In the code below, we use the Data property to pass some relevant data back to the caller.

        // Dog.Bark
        private int BarkInvokeCount = 0;
        public void Bark(int numTimes)

            if (numTimes > 12)
                Exception xx = new Exception("Too much barking");
                xx.Data.Add("Dog", this);
                xx.Data.Add("NumTimesParameter", numTimes);
                xx.Data.Add("ExceptionTime", DateTime.Now);
                xx.Data.Add("BarkInvokeCount", BarkInvokeCount);

                throw xx;

            Console.WriteLine(string.Format("{0}: Woof", Name));

When we catch the exception, we have access to this information:


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

4 Responses to #887 – Report Additional Data when You Throw an Exception

  1. Pingback: #888 – Objects Added to Exception’s Data Dictionary Must Be Serializable | 2,000 Things You Should Know About C#

  2. Pingback: #906 – Adding Custom Data vs. Using a Custom Exception Type | 2,000 Things You Should Know About C#

  3. Nabs says:

    Hi Sean,

    It was a helpful post. However, I just want to confirm, what version of Visual Studio is this supported?

    Thanks and more power!

    • Sean says:

      Thanks Nabs,

      The Exception.Data property isn’t related to Visual Studio. The property showed up in .NET Framework 2.0, so any version of the Framework since 2.0 will have it.


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 )

Connecting to %s

%d bloggers like this: