throw;
只是说和throw ex;
假设ex
是你正在捕捉的例外有区别吗?
问问题
35696 次
3 回答
44
throw ex;
将擦除您的堆栈跟踪。除非您要清除堆栈跟踪,否则不要这样做。只需使用throw;
于 2008-09-17T22:55:37.443 回答
18
这是一个简单的代码片段,有助于说明差异。不同之处在于 throw ex 将重置堆栈跟踪,就好像“ throw ex;
”行是异常的来源一样。
代码:
using System;
namespace StackOverflowMess
{
class Program
{
static void TestMethod()
{
throw new NotImplementedException();
}
static void Main(string[] args)
{
try
{
//example showing the output of throw ex
try
{
TestMethod();
}
catch (Exception ex)
{
throw ex;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine();
Console.WriteLine();
try
{
//example showing the output of throw
try
{
TestMethod();
}
catch (Exception ex)
{
throw;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
输出(注意不同的堆栈跟踪):
System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23
System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43
于 2008-09-17T23:10:45.863 回答
2
你有两个选择抛出;或将原始异常作为新异常的内部异常抛出。取决于你需要什么。
于 2008-09-17T23:03:26.833 回答