开发者

Exception throwing

开发者 https://www.devze.com 2022-12-22 21:46 出处:网络
In C#, will the folloing code throw e containin开发者_如何学Gog the additional information up the call stack?

In C#, will the folloing code throw e containin开发者_如何学Gog 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!


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号