gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:46:36 25 4
gpt4 key购买 nike

我的同事是经验丰富的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com