【问题标题】:Exception type that is not sufficiently specific error from StyleCop of VS2010来自 VS2010 的 StyleCop 的异常类型不够具体的错误
【发布时间】:2011-05-23 21:12:51
【问题描述】:

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

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.

我只是想在遇到一些错误情况时抛出一个错误。我怎样才能做出足够具体的例外?

【问题讨论】:

    标签: c# visual-studio-2010 stylecop


    【解决方案1】:

    抛出一个InvalidOperationException

    虽然微软过去在异常处理上并不一致,但这里是当前的Best Practices for Handling Exceptions

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

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

    以下是实现自定义异常的指南:Designing Custom Exceptions

    【讨论】:

    【解决方案2】:

    您可以扩展 Exception 并实现您自己的 Exception 类。如果您只是想欺骗 StyleCop,您甚至可以将其留空

    public Class MyException : Exception
    {
         public MyException(string errorMsg) : base(errorMessage) {}
    }
    

    然后

    throw new MyException("blah blah");
    

    【讨论】:

    • 您显示的异常的实现不完整
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 2020-04-23
    相关资源
    最近更新 更多