简体   繁体   English

抛出异常

[英]Exception throwing

In C#, will the folloing code throw e containing the additional information up the call stack? 在C#中,下面的代码是否会在调用堆栈中引入包含其他信息的e

...
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之前调用堆栈的调用。

...
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. 你可以这样做但是由于FxCop,我总是在抛出异常时创建自定义异常。 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. 如果您需要包含后续异常,则可以使用Exception的InnerException,或者只是为新Exception添加成员变量。

This tells you how to make you own successfully. 这告诉您如何让自己成功。 http://blog.gurock.com/articles/creating-custom-exceptions-in-dotnet/ 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: 这是我个人编程Zen的页面:

Your program is your house. 你的计划是你的房子。 Make it as nice as you can so it's easy and fun to live in. 让它变得尽可能好,这样生活起来既轻松又有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM