当捕获异常并重新抛出它们时,最好的做法是什么?我想确保Exception
对象的InnerException
和堆栈跟踪被保留.以下代码块在处理方式上是否存在差异?
try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
VS:
try
{
//some code
}
catch
{
throw;
}
当捕获异常并重新抛出它们时,最好的做法是什么?我想确保Exception
对象的InnerException
和堆栈跟踪被保留.以下代码块在处理方式上是否存在差异?
try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
VS:
try
{
//some code
}
catch
{
throw;
}
保留堆栈跟踪的方法是通过使用throw;
,这也是有效的
try {
// something that bombs here
} catch (Exception ex)
{
throw;
}
throw ex;
基本上类似于从该点引发异常,因此堆栈跟踪只会到达发出throw ex;
语句的位置.
假设异常允许您传递异常(推荐),Mike也是正确的.
Karl Seguin在他的foundations of programming e-book中也有great write up on exception handling分,这是一个很棒的读物.
编辑:Foundations of Programming pdf的工作链接.只需在文本中搜索"例外".