Reputation: 247
I'm looking for the appropriate exception to use for each static method in a class library that I have, as all the methods are related.
public static void EnterText(string element, string value, PropertyType elementType)
{
if (PropertiesCollection.Driver == null)
{
throw new InvalidOperationException();
}
if (elementType == PropertyType.Id)
{
PropertiesCollection.Driver.FindElement(By.Id(element)).SendKeys(value);
}
else if (elementType == PropertyType.Name)
{
PropertiesCollection.Driver.FindElement(By.Name(element)).SendKeys(value);
}
else //if elementType does not make sense an argument exception is thrown
{
throw new ArgumentException();
}
}
The problem is if the PropertiesCollection.Driver is not initialized, the method is useless. Therefore, I'd like to throw an exception if it is null when the method is called. The closest thing I have found to what I'm looking for is InvalidOperationException. However MSDN says it is an "exception that is thrown when a method call is invalid for the object's current state". Since it is a static class and thus has no objects, is this an inappropriate exception type? If no, then which exception should be thrown instead?
Also on more of the organizational side of things, should the code snippet that checks if the driver is null be at the top of each method, or is that too redundant? The alternative that I can think of is a helper method called at the beginning of each that checks and throws an exception if need be.
Upvotes: 0
Views: 228
Reputation: 12181
Some people may disagree with me but saying that InvalidOperationException is the wrong exception simply because there's not technically an instance seems like hair-splitting to me. This seems like a perfectly acceptable use of this exception to me.
I suppose you could create a helper function to test for this condition and decide if you should throw the InvalidOperationException but it truthfully doesn't seem all that worthwhile, plus it could, in my opinion, actually decrease the clarity of the code. The check isn't all that much code and, if I'm reading the code, I'd prefer to just see what checks are happening rather than having to dig into another method to figure it out.
Upvotes: 1