在捕获异常并重新抛出异常时,应该考虑哪些最佳实践?我想确保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;
}
当前回答
你也可以使用:
try
{
// Dangerous code
}
finally
{
// clean up, or do nothing
}
而抛出的任何异常都将上升到处理它们的下一层。
其他回答
我肯定会用:
try
{
//some code
}
catch
{
//you should totally do something here, but feel free to rethrow
//if you need to send the exception up the stack.
throw;
}
这将保护您的堆栈。
如果你抛出一个带有初始异常的新异常,你也会保留初始堆栈跟踪。
try{
}
catch(Exception ex){
throw new MoreDescriptiveException("here is what was happening", ex);
}
你也可以使用:
try
{
// Dangerous code
}
finally
{
// clean up, or do nothing
}
而抛出的任何异常都将上升到处理它们的下一层。
经验法则是避免捕获和抛出基本的Exception对象。这迫使你对异常更加聪明;换句话说,你应该有一个显式的SqlException捕捉,这样你的处理代码就不会对NullReferenceException做错误的事情。
不过,在现实世界中,捕获和记录基本异常也是一种很好的实践,但不要忘记遍历整个过程以获取可能存在的任何innerexception。
当抛出ex时,实际上是抛出了一个新的异常,并将错过原始的堆栈跟踪信息。Throw是首选的方法。