Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should be thrown?

I wrote a custom action method selector attribute that has three bool properties. It's invalid for all three of them to be false. At least one of them has to be true. When IsValidForRequest gets executed I check that at least one of them is true. But if none is, which exception should I throw?

Some relevant code:

public class MyCustomAttribute : ActionMethodSelectorAttribute
{
    public bool Prop1 { get; set; }
    public bool Prop2 { get; set; }
    public bool Prop3 { get; set; }

    public MyCustomAttribute()
    {
        this.Prop1 = true;
        this.Prop2 = true;
        this.Prop3 = true;
    }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        // at least one of them must be true
        if (!this.Prop1 && !this.Prop2 && !this.Prop3)
        {
            throw new ?????
        }

        // other codez here
    }
}

Attributes have this nice ability of initializing them while also providing property values, so I have to check them in the IsValidForRequest method.

[MyCustom(Prop1 = false, Prop2 = false, Prop3 = false)]

Which exception should be thrown?

like image 474
Robert Koritnik Avatar asked Feb 28 '11 17:02

Robert Koritnik


People also ask

Which exceptions can be thrown?

Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

Which exception can be thrown in Java?

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception.

When should a function throw an exception?

5.1 Understanding Exception HandlingIf the detecting function cannot deal with the anomaly, it "throws" an exception. A function that "handles" that kind of exception catches it. In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program.


1 Answers

I'd probably throw InvalidOperationException, because the operation is not valid for the object's current state.

like image 133
TrueWill Avatar answered Oct 20 '22 06:10

TrueWill