VS2010 的 StyleCop 中的异常类型不够具体错误
我有一些抛出异常的代码,如下所示。
if (jobFinished)
{
...
} else
{
throw new Exception("The server Error ...")
}
它编译/运行没有问题,但是当我运行 StyleCop 时,我收到此错误消息,指出异常不是特定的。
Error 10 CA2201 : Microsoft.Usage : Function(string, DirectoryInfo, string, string, string, out string)'
creates an exception of type 'Exception', an exception type that is not sufficiently
specific and should never be raised by user code. If this exception instance might be
thrown, use a different exception type.
我只想在遇到某些错误情况时抛出错误。我怎样才能做出足够具体的异常?
I have some code that throws an exception as follows.
if (jobFinished)
{
...
} else
{
throw new Exception("The server Error ...")
}
It compiles/runs without a problem, but when I run StyleCop, I got this error message saying Exception is not specific.
Error 10 CA2201 : Microsoft.Usage : Function(string, DirectoryInfo, string, string, string, out string)'
creates an exception of type 'Exception', an exception type that is not sufficiently
specific and should never be raised by user code. If this exception instance might be
thrown, use a different exception type.
I just want to throw an error when I encounter some error conditions. How can I make sufficiently specific Exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
抛出
InvalidOperationException
。尽管 Microsoft 过去在异常处理方面并不一致,但以下是当前的最佳处理异常的实践。
过去建议创建您自己的异常并从
ApplicationException
派生,但现在您应该从Exception
派生。如果您不需要区分方法中不同类型的失败,那么
InvalidOperationException
就足够了。否则,实现您自己的从 Exception 类派生的 Exception 类。以下是实现自定义异常的指南:设计自定义异常
Throw an
InvalidOperationException
.Although, Microsoft wasn't consistent on the exception handling in the past, here are current Best Practices for Handling Exceptions.
It was recommended in the past to create your own exception and derive from
ApplicationException
, but now you should derive fromException
.If you don't need to differentiate between different types of failure in your method then
InvalidOperationException
would be good enough. Otherwise, implement your own Exception classes that are derived fromException
class.Here are the guidelines for implementing custom Exceptions: Designing Custom Exceptions
您可以扩展 Exception 并实现您自己的 Exception 类。如果你只是想欺骗 StyleCop,你甚至可以将其
留空
You could just extend Exception and implement your own Exception class. You could probably even leave it empty if you wanted just to trick StyleCop
Then