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