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)]
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.
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.
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.
I'd probably throw InvalidOperationException
, because the operation is not valid for the object's current state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With