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

标签 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.
}

我在很多地方都看到过这样做。我真的想不出切断堆栈跟踪会有用的情况。我认为这应该是值得评论的特殊情况。如果我错了,请纠正我。如果要删除堆栈跟踪,我认为最好这样做:

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 Analysis 内置于 VS2010,但我不是 100% 确定...

这是 Microsoft download link for FxCop .

关于c# - 如何使用 StyleCop 或 VS2010 检测重新抛出 C# 异常的错误方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835506/

相关文章:

c# - ActiveX 控件名称不可用

c++ - 创建二维数组异常 : clean-up before re-throw in C++

java - 使用新消息重新抛出 java 异常,如果它在方法声明列表中,则保留异常类型

php - 在这种情况下我应该重新抛出异常吗?

c# - 如何将引发的异常从C#类传递到C#表单

c# 如何检测 Netflix 是否正在运行

c# - 如何添加评价我的应用程序按钮 (UWP)

c# - 如何删除 Xamarin.Forms 中的 (Android) 应用程序标题栏?

c# - 为了我们可以在其上放置 foreach,对集合的要求是什么?

c# - 重新抛出错误的堆栈跟踪