有什么可以导致抛出重置调用堆栈(我使用"抛出",不与QUOT;抛出前") [英] what can lead throw to reset a callstack (I'm using "throw", not "throw ex")

查看:164
本文介绍了有什么可以导致抛出重置调用堆栈(我使用"抛出",不与QUOT;抛出前")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为扔和扔恩之间的区别<一href="http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex">was抛出独显不复位异常的堆栈跟踪。

I've always thought the difference between "throw" and "throw ex" was that throw alone wasn't resetting the stacktrace of the exception.

不幸的是,这不是我遇到的行为;这里是一个简单的示例重现我的问题:

Unfortunately, that's not the behavior I'm experiencing ; here is a simple sample reproducing my issue :

using System;
using System.Text;

namespace testthrow2
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    throw new Exception("line 14");
                }
                catch (Exception)
                {
                    throw; // line 18
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

            }
            Console.ReadLine();
        }
    }
}

我希望这code打印调用栈起始于第14行;然而,调用堆栈开始于行。当然18是没什么大不了的样品中,但是在我的现实生活中的应用,失去了最初的错误信息是相当痛苦的。

I would expect this code to print a callstack starting at line 14 ; however the callstack starts at line 18. Of course it's no big deal in the sample, but in my real life application, losing the initial error information is quite painful.

我失去了一些东西明显?有另一种方式来达到我想要的(即重新不失堆栈信息抛出一个异常?)

Am I missing something obvious? Is there another way to achieve what I want (ie re throwing an exception without losing the stack information?)

我使用的是.NET 3.5

I'm using .net 3.5

推荐答案

您应该看看这篇文章:

  • <一个href="http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-$p$pserving-the-full-call-stack-trace.aspx">Rethrowing异常和preserving充分调用堆栈跟踪

总之,一般的preserves原来抛出的异常的堆栈跟踪,但前提是例外,没有发生在当前栈帧(即方法)。

In short, throw usually preserves the stack trace of the original thrown exception, but only if the exception didn't occur in the current stack frame (i.e. method).

有一种方法 preserveStackTrace (在博客文章中显示),您使用preserves原来的堆栈跟踪是这样的:

There is a method PreserveStackTrace (shown in that blog article) that you use that preserves the original stack trace like this:

try
{

}
catch (Exception ex)
{
    PreserveStackTrace(ex);
    throw;
}

但我通常的解决办法是,要么干脆被卡住,然后再像这样抛出异常(除非绝对必要),或者只是总是抛出使用的InnerException 属性的新例外传播最初的异常:

But my usual solution is to either simply to not catch and re throw exceptions like this (unless absolutely necessary), or just to always throw new exceptions using the InnerException property to propagate the original exception:

try
{

}
catch (Exception ex)
{
     throw new Exception("Error doing foo", ex);
}

这篇关于有什么可以导致抛出重置调用堆栈(我使用&QUOT;抛出&QUOT;,不与QUOT;抛出前&QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆