不正确堆栈跟踪被重新抛出

编程入门 行业动态 更新时间:2024-10-06 12:27:35
本文介绍了不正确堆栈跟踪被重新抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我重新抛出异常与扔;,但​​堆栈跟踪不正确:

静态无效的主要(字串[] args){    尝试{        尝试{            抛出新的异常(测试); // 12号线        }        赶上(例外前){            扔; // 15号线        }    }    赶上(例外前){        System.Diagnostics.Debug.Write(ex.ToString());    }    Console.ReadKey();}

正确的堆栈跟踪应该是:

System.Exception的:测试   在ConsoleApplication1.Program.Main(字串[] args)Program.cs中:12号线

但我得到:

System.Exception的:测试   在ConsoleApplication1.Program.Main(字串[] args)Program.cs中:15号线

但线15的位置抛;。我与.NET 3.5测试这一点。

解决方案

在同样的方法投掷两次可能是一个特例 - 我没有能够建立一个堆栈跟踪其中同样的方法不同线路相互跟随。正如一句话说,一个堆栈跟踪显示了堆栈帧的异常运行。还有每个方法调用只有一个堆栈帧!

如果你从另一个方法抛出,扔; 不会删除进入美孚(),符合市场预期

静态无效的主要(字串[] args)  {     尝试     {        Rethrower();     }     赶上(异常前)     {        Console.Write(ex.ToString());     }     Console.ReadKey();  }  静态无效Rethrower()  {     尝试     {        美孚();     }     赶上(异常前)     {        扔;     }  }  静态无效美孚()  {     抛出新的异常(测试);  }

如果您修改 Rethrower()和替换扔; 按罚球前; 的美孚()在堆栈跟踪项消失。再次,这是预期的行为。

I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) { try { try { throw new Exception("Test"); //Line 12 } catch (Exception ex) { throw; //Line 15 } } catch (Exception ex) { System.Diagnostics.Debug.Write(ex.ToString()); } Console.ReadKey(); }

The right stacktrace should be:

System.Exception: Test at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

解决方案

Throwing twice in the same method is probably a special case - I've not been able to create a stack trace where different lines in the same method follow each other. As the word says, a "stack trace" shows you the stack frames that an exception traversed. And there is only one stack frame per method call!

If you throw from another method, throw; will not remove the entry for Foo(), as expected:

static void Main(string[] args) { try { Rethrower(); } catch (Exception ex) { Console.Write(ex.ToString()); } Console.ReadKey(); } static void Rethrower() { try { Foo(); } catch (Exception ex) { throw; } } static void Foo() { throw new Exception("Test"); }

If you modify Rethrower() and replace throw; by throw ex;, the Foo() entry in the stack trace disappears. Again, that's the expected behavior.

更多推荐

不正确堆栈跟踪被重新抛出

本文发布于:2023-11-12 20:57:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582511.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   不正确   抛出

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!