In C#, will the folloing code throw e
containing the additional information up the call stack?
...
catch(Exception e)
{
e.Data.Add("Additional information","blah blah");
throw;
}
In C#, will the folloing code throw e
containing the additional information up the call stack?
...
catch(Exception e)
{
e.Data.Add("Additional information","blah blah");
throw;
}
Yes, it will. A lot of developers don't realise that the following code will throw a new exception from that point in the call-stack, not the calls made previously up the stack before the catch
.
...
catch(Exception e)
{
e.Data.Add("Additional information","blah blah");
throw e;
}
I learnt this the hard way!
Exceptions are not immutable, and being able to add information to them is one reason for this.
So, yes, the data will be added to the exception information bubbling up.
var answer = "No";
try
{
try
{
throw new Exception();
}
catch (Exception e)
{
e.Data.Add("mykey", "myvalue");
throw;
}
}
catch (Exception e)
{
if((string)e.Data["mykey"] == "myvalue")
answer = "Yes";
}
Console.WriteLine(answer);
Console.ReadLine();
When you run the code you will find that the answer is yes :-)
You can do this but due to FxCop I've always created custom exceptions when ever I throw and exception. This gives the caller the ability to easily catch and understand different types of errors. If you need to include a subsequent exception you can use the InnerException of Exception or simply ad a member variable for your new Exception.
This tells you how to make you own successfully. http://blog.gurock.com/articles/creating-custom-exceptions-in-dotnet/
This is one of those programming things that people like to skip because it simply extra work to get an application functional.
This is a page from my personal Zen of Programming:
Your program is your house. Make it as nice as you can so it's easy and fun to live in.