Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检测使用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. }_C#_Rethrow - Fatal编程技术网

如何检测使用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. }

如何检测使用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. },c#,rethrow,C#,Rethrow,我在很多地方都看到过这种做法。我真的想不出在什么情况下切断堆栈跟踪会有用。我认为这应该是一个值得评论的特殊情况。如果我错了,请纠正我。如果要剪切堆栈轨迹,我认为最好执行以下操作: throw new ArgumentException("text", ae /* inner exc */); 无论如何,我要做的是检测所有此类情况并发出警告。正则表达式搜索没有帮助,因为: catch(Exception e) { Exception newExc = new Exception("tex

我在很多地方都看到过这种做法。我真的想不出在什么情况下切断堆栈跟踪会有用。我认为这应该是一个值得评论的特殊情况。如果我错了,请纠正我。如果要剪切堆栈轨迹,我认为最好执行以下操作:

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对此有一个规则:

一旦抛出异常,部分 它携带的信息是 堆栈跟踪。堆栈跟踪是一个列表 方法调用层次结构的 从抛出 异常,并以方法结束 这是个例外。如果 通过指定 抛出语句中的异常, 堆栈跟踪将在 当前方法和方法列表 在原始方法之间调用 引发了异常和当前 方法丢失。保留原件 将跟踪信息与 异常,请使用throw语句 没有指定异常

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


这是一个很好的观点,但出于某种原因,我们的日志框架希望我们提供它发生的位置。就地抓捕似乎是一个显而易见的解决办法。有时异常处理逻辑甚至更复杂。好吧,将异常传递给日志框架,然后日志框架可以使用Exception.StackTrace获取错误的位置。酷…这在VS2008中称为代码分析。我猜这条规则是从FxCop继承过来的。等等,你是如何从VS2008开始代码分析的?@ShellShock——引起你的注意。VS2008中的代码分析在哪里?在VS团队系统版中。那个昂贵的。VS2010 Prof也没有,至少是Premium。项目属性,代码分析选项卡。