views:

37

answers:

3

I have some trouble for choosing the right type of exception to throw when an expected custom attribute is not found (I would prefer one of the existing .NET exceptions).

What do you recommend in this case? Thanks in advance.

Edit:

Here his the context:

[<ExpectedAttribute()>]
let foo args ... = ...

The function foo (which is user-defined) is passed to a runtime engine. The runtime have to throw an exception if the custom attribute is not present.

+1  A: 

If a custom attribute is missing, it is not going to fit a System exception.

You could use a System exception, but what is your domain here? And what sort of contract is broken? It matters if this is about serialization or testing or ...


Edit, after your foo addition: The closet you come with the System exceptions is System.ArgumentException , because your engine is receiving a parameter that does not meet its requirements.

But I would define a MissingExpectedAttribute exception.

Henk Holterman
Thanks. About `InvalidArgument`, do you mean `System.ArgumentException` ? (because there is no `System.InvalidArgumentException`)
Stringer Bell
@Stringer: Yes, I was relying on memory again. Will edit.
Henk Holterman
+1  A: 

I would suggest something general like "InvalidOperationException" or "InvalidArgumentException" and put the details about the expected attribute in the message.

Cylon Cat
`InvalidOperationException` would be appropriate, but `InvalidArgumentException` wouldn't be, `ArgumentException` and subtypes are defined explicitly to be about method argument validation.
Richard
Neither one is specific enough, but you're right, InvalidOperation is a little closer. A custom exception is probably the best solution.
Cylon Cat
+1  A: 

If the constructor, method or property called was given the rule-breaking object, then ArgumentException. If the rule-breaking object was part of your state from a previous operation, and then the method or property that insists upon this attribute being present was called, the InvalidOperation.

Jon Hanna