不正确堆栈跟踪被重新抛出 [英] Incorrect stacktrace by rethrow

查看:191
本文介绍了不正确堆栈跟踪被重新抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 静态无效的主要(字串[] 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.

这篇关于不正确堆栈跟踪被重新抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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