【发布时间】:2012-09-11 15:28:18
【问题描述】:
普遍认为,在 .NET 中 throw; 不会重置堆栈跟踪,但 throw ex; 会。
但是,在这个简单的程序中,我得到了不同的行号:
void Main()
{
try
{
try
{
Wrapper(); // line 13
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
throw; // line 18
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void Wrapper()
{
Throw(); // line 28
}
public void Throw()
{
var x = (string)(object)1; // line 33
}
输出是:
System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型。 在 C:\long-path\Program.cs:line 13 中的 ConsoleApplication2.Program.Main(String[] args) 处
System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型。 在 C:\long-path\Program.cs:line 18 中的 ConsoleApplication2.Program.Main(String[] args) 处
注意:第一个堆栈跟踪包含第 13 行,第二个包含第 18 行。此外,第 13 行和第 18 行都不是实际发生强制转换的行。
我现在的问题是:throw; 在什么情况下会更改堆栈跟踪,在什么情况下不会更改堆栈跟踪?
请注意,这已经been observed,但一般没有回答。
更新:
我在调试模式下运行了上面的代码,结果如下:
System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型。 在 C:\long-path\Program.cs:line 33 中的 ConsoleApplication2.Program.Throw() 在 C:\long-path\Program.cs:line 28 中的 ConsoleApplication2.Program.Wrapper() 在 C:\long-path\Program.cs:line 13 中的 ConsoleApplication2.Program.Main(String[] args) 处
System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型。 在 C:\long-path\Program.cs:line 33 中的 ConsoleApplication2.Program.Throw() 在 C:\long-path\Program.cs:line 28 中的 ConsoleApplication2.Program.Wrapper() 在 C:\long-path\Program.cs:line 18 中的 ConsoleApplication2.Program.Main(String[] args) 处
请注意:最后的行号仍然改变
【问题讨论】:
-
如果异常中详述的行号与您提供的代码的 sn-p 相关联会有所帮助...