Recipe 7.18. Giving Exceptions the Extra Info They Need with Exception.DataProblemYou want to send some additional information along with an exception. SolutionUse the Data property on the System.Exception object to store key-value pairs of information relevant to the exception. For example, say there is a System.ArgumentException being thrown from a section of code and you want to include the underlying cause and the length of time it took. The code would add two key-value pairs to the Exception.Data property by specifying the key in the indexer and then assigning the value. In the example that follows, the Data for the irritable exception uses "Cause" and "Length" for its keys. Once the items have been set in the Data collection, the exception can be thrown and caught, and more data can be added in subsequent catch blocks for as many levels of exception handling as the exception is allowed to traverse. try { try { try { try { ArgumentException irritable = new ArgumentException("I'm irritable!"); irritable.Data["Cause"]="Computer crashed"; irritable.Data["Length"]=10; throw irritable; } catch (Exception e) { // See if I can help… if(e.Data.Contains("Cause")) e.Data["Cause"]="Fixed computer"; throw; } } catch (Exception e) { e.Data["Comment"]="Always grumpy you are"; throw; } } catch (Exception e) { e.Data["Reassurance"]="Error Handled"; throw; } } The final catch block can then iterate over the Exception.Data collection and display all of the supporting data that has been gathered in the Data collection since the initial exception was thrown: catch (Exception e) { Console.WriteLine("Exception supporting data:"); foreach(DictionaryEntry de in e.Data) { Console.WriteLine("\t{0} : {1}",de.Key,de.Value); } } DiscussionException.Data is an object that supports the IDictionary interface. This allows you to:
It is a very handy thing to be able to tack on code-specific data to the system exceptions, as it provides the ability to give a more complete picture of what happened in the code when the error occurred. The more information available to the poor soul (probably yourself) who is trying to figure out why the exception was thrown in the first place, the better the chance of it being fixed. Do yourself and your team a favor and give a little bit of extra information when throwing exceptions; you won't be sorry you did. See AlsoSee the "Exception.Data Property" topic in the MSDN documentation. |