异常类型,不是来自VS2010的StyleCop的足够具体的错误

pro*_*eek 4 c# stylecop visual-studio-2010

我有一些引发异常的代码如下。

if (jobFinished)
{
   ...                
} else
{                  
    throw new Exception("The server Error ...")
}
Run Code Online (Sandbox Code Playgroud)

它可以编译/运行,没有问题,但是当我运行StyleCop时,出现了此错误消息,指出Exception不特定。

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.
Run Code Online (Sandbox Code Playgroud)

我遇到一些错误情况时只想抛出一个错误。如何做出足够明确的异常?

Ale*_*Aza 5

扔一个InvalidOperationException

尽管Microsoft过去在异常处理方面并不一致,但是这里是最新的异常处理最佳实践

过去曾建议创建自己的异常并从中派生ApplicationException,但现在应该从中派生Exception

如果您不需要在方法中区分不同类型的失败,那么InvalidOperationException就足够了。否则,请实现自己的从Exception类派生的Exception 类。

以下是实现自定义例外的准则:设计自定义例外