如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1559字,纯文字阅读大概需要3分钟。
内容图文
![如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?](/upload/InfoBanner/zyjiaocheng/821/0f2c0eb36ce54ccc965a072836ebec72.jpg)
我的同事经验丰富的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.
内容总结
以上是互联网集市为您收集整理的如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?全部内容,希望文章能够帮你解决如何使用StyleCop或VS2010检测重新抛出C#异常的坏方法?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。