本文介绍了什么可以导致重置一个callstack(我使用“throw”,而不是“throw ex”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为throw和throw ex之间的区别



不幸的是,这不是我遇到的行为;这里是一个简单的例子,说明我的问题:

  using System; 
使用System.Text;

命名空间testthrow2
{
类程序
{
static void Main(string [] args)
{
try
{
try
{
throw new Exception(line 14);
}
catch(异常)
{
throw; // line 18
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());

}
Console.ReadLine();
}
}
}

我希望这段代码打印从第14行开始的呼叫堆栈;然而,callstack从第18行开始。当然,在样本中没有什么大不了的,但在我的现实生活中,丢失初始错误信息是相当痛苦的。



我缺少一些明显的东西有没有另一种方式来实现我想要的(即重新抛出异常而不丢失堆栈信息?)



我使用的是.net 3.5

解决方案

您应该阅读这篇文章:







简而言之, throw 通常保留原始抛出异常的堆栈跟踪,但只有当当前堆栈帧中没有发生异常(即方法)时。



您使用的方法 PreserveStackTrace (显示在该博客文章中),保留原始的堆栈跟踪,如下所示:

  try 
{

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

但我通常的解决方案是简单地不抓住并重新抛出异常这个(除非是绝对必要的),或者只是总是使用 InnerException 属性来抛出新的异常来传播原始异常:

  try 
{

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


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();
        }
    }
}

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

I'm using .net 3.5

解决方案

You should read this article:

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

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;
}

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);
}

这篇关于什么可以导致重置一个callstack(我使用“throw”,而不是“throw ex”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 17:37