tags:

views:

305

answers:

2

What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot?

+22  A: 

InvalidOperationException maybe?

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

Michael Stum
More and more people should use InvalidOperationException instead of creating new ones.
JaredPar
Thanks! I knew there had to be something.
Chris Marasti-Georg
True, or at least derive from it so that catching InvalidOperationException also catches the derived one. Look at the Exceptions that derive from IOE (bottom of the MSDN) to see when it could make sense to roll your own.
Michael Stum
Not the most obvious name.
James McMahon
it depends. You are trying to perform an Invalid Operation after all, but there are many ways to name it.
Michael Stum
+1  A: 

If at all I'd say System.InvalidProgramException get nearest to what you want. What's wrong with throwing a custom exception?

Markus Nigbur
IPE: "The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program.". Using Standard Exceptions creates consistency around the framework and third party apps.
Michael Stum
There is nothing wrong with custom exceptions if there is nothing in the framework to support your case. I could write a custom ArrayList, but why would I?
Chris Marasti-Georg
ok, like pYrania I don't get either why do you think this is so important? You have to write SOME code to implement ArrayList, but this cannot be compared to create a custom exception...
botismarius
The point is that you should not duplicate existing functionality. If I throw a custom exception, that is another thing that a programmer using my library has to learn. If I follow the conventions of the framework, I allow them to leverage their existing knowledge.
Chris Marasti-Georg
Yes, but nevertheless you should write a documentation for your library. Giving that, for a user it shouldn't matter if the exception you throw is Exception1 or Exception2.
botismarius