views:

21

answers:

3

Hi!

We have a WebForms Control which requires that the ID of another Control implementing ITextControl is provided.

What exception should we throw if there is no control with that ID or a control is found but it's not implementing the interface?

var text = Page.FindControl(TextProviderId) as ITextControl;

if (text == null) {
   throw new WhatEverException(...);
...

Should we split it into two cases and throw one exception if there is no control with that ID, and another one if said control does not implement ITextControl? If so, which exceptions should we use then?

A: 

ArgumentOutOfRangeException?

GSerg
@Anonymous downvoter: As stated in the linked MSDN article, this exception is for cases when the argument does not belong the set of allowed values, where "allowed values" has different meaning depending on the context. It the passed ID does not represent an existing control that implements a certain interface, then it does not belong to the set of allowed arguments.
GSerg
A: 

Whether or not you should split them up into different exceptions probably depends most on whether or not you think it is likely that anyone will ever want to distinguish the two exceptions in different catch blocks.

Not knowing exactly how this will be used, this seems like the kind of error that should be brought to the developer's attention, where rewriting code to point to the correct file or implement the correct interface is the proper action, rather than implementing a try-catch and give the user friendly error messages. As such, I'd just throw an ArgumentException.

David Hedlund
+2  A: 

If the control should really be there, I would say that your web form is in an invalid state if it is missing, so I would probably go for InvalidOperationException:

The exception that is thrown when a method call is invalid for the object's current state.

This would be applicable to both scenarios; regardless of whether the control is missing or if it does not implement the expected interface, the containing object is in an invalid state.

If this is a scenario that is expected to happen for various reasons (let's say that you are making some tool that others will program against, and this is a situation that they might very well produce), perhaps you should instead create two custom exceptions that make it very clear what is happening and how to correct it (such as ControlNotFoundException and InterfaceNotFoundException or something similar).

Fredrik Mörk
It will of course also need to be called with detailed message describing which control that was supposed to be there.
awe