我写了一个快速测试来显示差异。这是测试代码:
try
{
var broken = int.Parse("null");
}
catch (Exception ex1)
{
System.Diagnostics.Trace.WriteLine(ex1.ToString());
}
try
{
try
{
var broken = int.Parse("null");
}
catch (Exception)
{
throw;
}
}
catch (Exception ex2)
{
System.Diagnostics.Trace.WriteLine(ex2.ToString());
}
try
{
try
{
var broken = int.Parse("null");
}
catch (Exception ex3)
{
throw ex3;
}
}
catch (Exception ex4)
{
System.Diagnostics.Trace.WriteLine(ex4.ToString());
}
运行它,我得到以下输出:
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at QuickTests.Program.Main(String[] args) in C:\Projects\Test\QuickTests\Program.cs:line 18
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
A first chance exception of type 'System.FormatException' occurred in QuickTests.exe
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at QuickTests.Program.Main(String[] args) in C:\Projects\Test\QuickTests\Program.cs:line 33
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
A first chance exception of type 'System.FormatException' occurred in QuickTests.exe
System.FormatException: Input string was not in a correct format.
at QuickTests.Program.Main(String[] args) in C:\Projects\Test\QuickTests\Program.cs:line 49
您会注意到前两个异常的工作方式相同。所以,“扔;” 就堆栈向上移动的异常而言,不会改变任何东西。然而“抛出 ex3;” 导致报告的异常不同,从而更改异常的堆栈跟踪。