<分区>
Possible Duplicate:
incorrect stacktrace by rethrow
人们普遍认为,在 .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: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 13
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 18
注意:第一个堆栈跟踪包含第 13 行,第二个堆栈跟踪包含第 18 行。此外,第 13 行和第 18 行都不是实际发生转换的行。
我现在的问题是:throw;
在什么情况下会更改堆栈跟踪,在什么情况下不会更改堆栈跟踪?
请注意,这已经是been observed , 但一般没有回答。
更新:
我在 Debug模式下运行上面的代码,结果如下:
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Throw() in C:\long-path\Program.cs:line 33 at ConsoleApplication2.Program.Wrapper() in C:\long-path\Program.cs:line 28 at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 13
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Throw() in C:\long-path\Program.cs:line 33 at ConsoleApplication2.Program.Wrapper() in C:\long-path\Program.cs:line 28 at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 18
请注意:最后一行的数字仍然在变化