prosseek
prosseek

Reputation: 190809

Exception type that is not sufficiently specific error from StyleCop of VS2010

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?

Upvotes: 6

Views: 5298

Answers (2)

Alex Aza
Alex Aza

Reputation: 78457

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 from Exception.

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 from Exception class.

Here are the guidelines for implementing custom Exceptions: Designing Custom Exceptions

Upvotes: 7

alexD
alexD

Reputation: 2364

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

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

Then

throw new MyException("blah blah");

Upvotes: 0

Related Questions