So, I was thinking about writing custom exceptions today, and considered the invalid operation exception. This exception can mean many many things, and in some actions, the operations might be invalid due to multiple independent causes. Consider this example. (And yes, I know that an ArgumentException would be better here, but I'm trying to come up with a simple example of an invalid operation exception)
public GetLocationFromLatLong(float Lat, float Long){
if ( Lat < -90 || Lat > 90){
throw new InvalidOperationException("Latitude is out of bounds")
}
if ( Long < -180 || Long > 180){
throw new InvalidOperationException("Longitude is out of bounds")
}
/*Actual function here*/
}
If I wanted to handle the above exception, I would need to inspect the message to see which argument was out of range, and then prompt the user. While this isn't exactly BAD, the method could alternatively throw something like "InvalidLatitude" and "InvalidLongitude" exceptions (both of which would inherit from System.InvalidOperationException and be functionally identical), and I could catch either of those individually and take action from that. The question is, these exceptions would be structurally no different than System.InvalidOperationException, so I would be adding another layer of abstraction on to the code that may not be necessary.
I feel like this would make code more readable in some instances, but at the same time I've often heard that "Less is more" in terms of coding. Is this a code smell, or is there a reason to not do this?
ArgumentException
/InvalidOperationException
is rarely a good idea. Normally those should only be thrown when you have a bug.