As I begin this blog entry, it is early in the day, so I do not yet know if this will be an exceptional day. Nevertheless, I would like to talk about exceptions.
All exceptions have a Data property, which can be very useful. I cannot say whether or not Microsoft uses it for any of their exception handling, say, for example, within their applications such as Excel, or within the code for their .NET framework. However, I can say that I have never seen it used in any projects I have been involved with over the last seven years in the .NET world.
Notice the Data property in the following listing for the ‘ex’ variable in the Watch1 window:
It is obviously empty in this case. However, observe that it is a free-form dictionary. It has
a Keys collection and a Values collection. The elements of both are of type object. Thus you can add just about anything that you feel might be useful to this dictionary. (NOTE: If this illustration or any other is too small for you to read, just double-click it to temporarily view it in a separate window. Then navigate back to the original page.)
To illustrate the use of the Data property, I have, believe it or not, developed a simple application that brews beer. A brewing application must have a Beer class, so here it is:
Since I have not yet perfected the brewing process, the Brew method throws an ApplicationException. To assist with determining what the error might be, the Brew method adds the value of the makeDark local variable and the Beer instance that caused the exception to the Data dictionary.
The main program, which defined the beer and initiated the brewing process, needs to collect this information, so that I can achieve perfection:
Here is the output:
Now, you might say that I could have developed a custom BrewingException class which included the two elements that I placed in the dictionary. This is true. However, even when using a custom exception class, I am sure you can imagine situations where you might like to collect additional information. This is a perfect job for the Exception class’s Data dictionary.
I hope you have an Exceptional day!

No comments:
Post a Comment