为什么在处理Action的方法中截断堆栈跟踪? [英] Why does catch in a method handling an Action truncate the stack trace?

查看:94
本文介绍了为什么在处理Action的方法中截断堆栈跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个小程序。如果您愿意,请忽略通用捕获,我将简短地尝试说明这一点:

Consider this small program. Ignore, if you will, the generic catch, I've kept it brief to try and illustrate the point:

private static void Main(string[] args)
{
    Try(Fail);
}

private static void Fail()
{
    var x = ((string)null).Clone();
}

private static void Try(Action action)
{
    try
    {
        action();
    }
    catch (Exception exc)
    {
        Debug.WriteLine(exc.StackTrace);                
    }
}

运行时,以下内容(带有一些路径)信息已删除):

When run, the following (with some of the path info removed) is produced:

at Scratch.Program.Fail() in Program.cs:line 27
at Scratch.Program.Try(Action action) in Program.cs:line 34

我的问题是-为什么异常的堆栈跟踪是否停止在 Try()方法中展开方法链?我希望它能解决 Main()方法的问题。

My question is - why does the stack trace of the exception stop unwinding the method chain at the Try() method? I would expect it to unwind past that to the Main() method.

我无法可以找到有关阻止异常结束的任何文档,这些文档可以通过 Try()-所以我想理解这一点。

I haven't been able to find any documentation about what it is that stops exception unwinding going past the Try() - so I'd like to understand this.

推荐答案

Exception.Stacktrace 调用 GetStackTrace 最终将调用

new StackTrace (此/ *例外对象* /,是)。与这些参数一起使用时,将评估堆栈跟踪的异常点,直到当前方法为止。您可以在添加

Exception.Stacktrace calls GetStackTrace which in the end will call
new StackTrace(this /* exception object */, true). When used with these parameters the stack trace will be evaluated for the point of the exception until the current method. You can check that yourself when adding

catch (Exception exc)
{
    Debug.WriteLine(new StackTrace());
    Debug.WriteLine(new StackTrace(exc, true));          
}

第二个版本是 exc返回的堆栈跟踪。 StackTrace ,第一个是从当前方法到入口点或线程开始的完整堆栈跟踪。

The second version is the stacktrace returned by exc.StackTrace, the first is the full stacktrace from the current method to the entry point or thread start.

这篇关于为什么在处理Action的方法中截断堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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