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

Ham*_*jan 4 c# rethrow

我的同事经验丰富的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.
}
Run Code Online (Sandbox Code Playgroud)

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

throw new ArgumentException("text", ae /* inner exc */);
Run Code Online (Sandbox Code Playgroud)

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

catch(Exception e)
{
    Exception newExc = new Exception("text", e);
    Log(newExc);
    throw newExc;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Aus*_*nen 5

FxCop有一个规则: RethrowToPreserveStackDetails

抛出异常后,它携带的部分信息就是堆栈跟踪.堆栈跟踪是方法调用层次结构的列表,该方法调用层次结构以抛出异常的方法开始,并以捕获异常的方法结束.如果通过在throw语句中指定异常来重新抛出异常,则会在当前方法重新启动堆栈跟踪,并且抛出异常的原始方法与当前方法之间的方法调用列表将丢失.要保留包含异常的原始堆栈跟踪信息,请使用throw语句而不指定异常.

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

这是FxCopMicrosoft下载链接.

  • 项目属性,代码分析选项卡. (2认同)