tags:

views:

135

answers:

4
+10  Q: 

Exception throwing

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;
}
+11  A: 

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!

Andy Shellam
+1 for the anti-example :)
Pharabus
Here is the article from Eric Lippert: http://blogs.msdn.com/ericlippert/archive/2010/03/04/too-much-reuse.aspx"The “throw;” does not reset the stack trace, “throw ex;” does"
ram
+1  A: 

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.

Oded
+4  A: 
        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 :-)

klausbyskov
...very funny ;)
Ben Aston
+1  A: 

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.

madmik3
+1 for the suggestion of creating/catching custom exceptions. It obviously does depend if you have control over the code that throws the exception you're catching, if it's a third party library you're a bit stuck with whatever exceptions it throws ;-)
Andy Shellam