Alex Rivera | Logout

C# what kind of exception should I raise?

Asked 2009-02-06T17:58:38.260
14

I am currently in a try catch finding if a property has been set properly to the bool value that it should be like this...

public void RunBusinessRule(MyCustomType customType)
{
    try
    {
       if (customType.CustomBoolProperty == true)
       {
            DoSomething(); 
       }
       else
       {
            throw new Exception("This is obviously false or possibly null lets throw up an error.");
       }
    }
    catch(Exception)
    {
        throw;
    }
}

Now the deal with throwing this error for me is that I am using Microsoft's source analysis and it gives me an error stating "CA2201 : Microsoft.Usage : Object.RunBusinessRule(MyCustomType)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.

Soooo What exception should I throw that would be specific enough for Microsoft.., for the circumstance of throwing an error about my own application's logic handling and when I want to "throw".

c#
Edit
Report

2 Answers

21
ArgumentException
InvalidOperationException
FormatException

The passed in argument wasn't good.

answered 2009-02-06T18:02:32.590
1

A slight aside, but you could simplify your code somewhat...

public void RunBusinessRule(MyCustomType customType)
{
    if (customType.CustomBoolProperty == false)
    {
        throw new Exception("This is obviously false or possibly null lets throw up an error.");
    }

    DoSomething(); 
}

As for the type of exception to throw, you might consider ApplicationException or InvalidOperationException, or you could define your own exception type.

answered 2009-02-06T18:03:48.937

Your Answer