编程语言
首页 > 编程语言> > 如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?

如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?

作者:互联网

我的同事经验丰富的C黑客转而使用.Net.他们无意中犯的一个错误就是编写如下代码:

catch(ArgumentExcepttion ae)
{
    // Code here logs the exception message
    // And this is supposed to re-throw the exeception
    throw ae; // as opposed to throw;
    // But, as we all know, doing this creates a new exception with a shorter stack trace.
}

我在许多地方看到过这种情况.我真的不能想到切断堆栈跟踪会有用的情况.我认为这应该是特殊的情况值得评论.如果我错了,请纠正我.如果要切割堆栈跟踪,我认为总是做得更好:

throw new ArgumentException("text", ae /* inner exc */);

无论如何,我想做的是检测所有这些情况并发出警告.正则表达式搜索无济于事,因为:

catch(Exception e)
{
    Exception newExc = new Exception("text", e);
    Log(newExc);
    throw newExc;
}

我将不得不使用StyleCop之类的工具(我有4.3.3.0版本).我现在正在使用VS2008,但很快就会转向VS2010.

关于如何完成我想要的任何想法?

解决方法:

FxCop有一个规则:RethrowToPreserveStackDetails

Once an exception is thrown, part of
the information it carries is the
stack trace. The stack trace is a list
of the method call hierarchy that
starts with the method that throws the
exception and ends with the method
that catches the exception. If an
exception is re-thrown by specifying
the exception in the throw statement,
the stack trace is restarted at the
current method and the list of method
calls between the original method that
threw the exception and the current
method is lost. To keep the original
stack trace information with the
exception, use the throw statement
without specifying the exception.

我相信FxCop分析是内置于VS2010但我不是100%肯定…

这是Microsoft download link for FxCop.

标签:c,rethrow
来源: https://codeday.me/bug/20190526/1158917.html