We're all familiar (i hope :)) with this construct:
try
{
// ... some code here ...
}
catch (Exception ex)
{
// one of these 2 lines are usually seen
throw; // presereves the full call stack
//throw ex; // changes the origin of exception to this method
}
finally
{
// more stuff here
}
It's a standard error catching routine in .Net.
But what if you want to pass some user info back to the caller method with the Exception being thrown?
Reader... meet Exception.Data. Exception.Data... meet reader.
Now that you're both properly aquainted let see what it does.
Exception.Data is a dictionatry that holds object for key and value. This means that you can put anything into it.
Here's how my standard catch code part looks like:
catch (Exception ex)
{
// pass the ex to preserve full stac trace
Exception exNew = new Exception("New exception message", ex);
exNew.Data.Add("string Data", "data");
exNew.Data.Add("int data", 1);
exNew.Data.Add("bool data", true);
exNew.Data.Add("DateTime data", DateTime.Now);
// full ex info with user data
throw exNew;
}
I've seen a lot of code and i've never seen this being used. I have seen other way overcomplicated methods being used for the same functionality though. :)
Even though .Data is the first property in the Exception intellisense list it gets overlooked. How? I have no idea.