参考网上的很多文档,特别是关于SO的文档,例如:在 C# 中重新引发异常的正确方法是什么? https://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c“扔 e;” 之间应该有区别和“扔;”。
但是,从:http://bartdesmet.net/blogs/bart/archive/2006/03/12/3815.aspx http://bartdesmet.net/blogs/bart/archive/2006/03/12/3815.aspx,
这段代码:
using System;
class Ex
{
public static void Main()
{
//
// First test rethrowing the caught exception variable.
//
Console.WriteLine("First test");
try
{
ThrowWithVariable();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
//
// Second test performing a blind rethrow.
//
Console.WriteLine("Second test");
try
{
ThrowWithoutVariable();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private static void BadGuy()
{
//
// Some nasty behavior.
//
throw new Exception();
}
private static void ThrowWithVariable()
{
try
{
BadGuy();
}
catch (Exception ex)
{
throw ex;
}
}
private static void ThrowWithoutVariable()
{
try
{
BadGuy();
}
catch
{
throw;
}
}
}
给出以下结果:
$ /cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319/csc.exe Test.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
$ ./Test.exe
First test
at Ex.ThrowWithVariable()
at Ex.Main()
Second test
at Ex.ThrowWithoutVariable()
at Ex.Main()
这与博客文章完全矛盾。
使用以下代码可以获得相同类型的结果:http://crazorsharp.blogspot.com/2009/08/rethroing-exception-without-resetting.html http://crazorsharp.blogspot.com/2009/08/rethrowing-exception-without-resetting.html
原问题: 我究竟做错了什么 ?
UPDATE:与 .Net 3.5 / csc.exe 3.5.30729.4926 的结果相同
SUMUP: 您的回答都很好,再次感谢。
所以原因是由于 64 位 JITter 导致有效内联。
我只能选择一个答案,这就是我选择的原因LukeH回答 :
然而这个问题现在又引发了另一个问题:此行为是否符合所有 .Net 规范:CLR 规范和 C# 编程语言规范?
UPDATE:根据以下标准,此优化似乎符合:抛出 VS 重新抛出:结果相同吗? https://stackoverflow.com/questions/3552125/throw-vs-rethrow-same-result/3552244#3552244(谢谢0xA3)
在此先感谢您的帮助。