在捕获异常并重新抛出异常时,应该考虑哪些最佳实践?我想确保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
}
而抛出的任何异常都将上升到处理它们的下一层。
其他回答
供参考,我刚刚测试了这个,'throw;'报告的堆栈跟踪不是完全正确的堆栈跟踪。例子:
private void foo()
{
try
{
bar(3);
bar(2);
bar(1);
bar(0);
}
catch(DivideByZeroException)
{
//log message and rethrow...
throw;
}
}
private void bar(int b)
{
int a = 1;
int c = a/b; // Generate divide by zero exception.
}
堆栈跟踪正确地指向异常的起源(报告的行号),但为foo()报告的行号是抛出的行;语句,因此您无法判断是哪个对bar()的调用导致了异常。
我肯定会用:
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;
}
这将保护您的堆栈。
你应该总是使用"throw;"来重新抛出。net中的异常,
请参考这个, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx
基本上MSIL (CIL)有两个指令——“throw”和“rethrow”:
c#的"throw ex;"被编译成MSIL的"throw" c#的“扔”;-进入MSIL“重扔”!
基本上,我可以看到为什么“throw ex”覆盖堆栈跟踪的原因。
如果你抛出一个带有初始异常的新异常,你也会保留初始堆栈跟踪。
try{
}
catch(Exception ex){
throw new MoreDescriptiveException("here is what was happening", ex);
}
保存堆栈跟踪的方法是使用throw;这也是有效的
try {
// something that bombs here
} catch (Exception ex)
{
throw;
}
把交货;基本上就像从那个点抛出一个异常,所以堆栈跟踪只会到你发出throw ex的地方;声明。
Mike也是正确的,假设异常允许您传递一个异常(这是推荐的)。
Karl Seguin在他的编程基础电子书中也写了一篇关于异常处理的很棒的文章,非常值得一读。
编辑:编程基础的工作链接pdf。在文本中搜索“例外”即可。