Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception throwing

Tags:

c#

exception

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;
}
like image 738
Ben Aston Avatar asked Mar 16 '10 12:03

Ben Aston


2 Answers

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!

like image 127
Andy Shellam Avatar answered Sep 27 '22 23:09

Andy Shellam


        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 :-)

like image 27
Klaus Byskov Pedersen Avatar answered Sep 27 '22 21:09

Klaus Byskov Pedersen