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?
views:
305answers:
2
+22
A:
InvalidOperationException maybe?
The exception that is thrown when a method call is invalid for the object's current state.
Michael Stum
2008-11-03 20:19:29
More and more people should use InvalidOperationException instead of creating new ones.
JaredPar
2008-11-03 20:22:06
Thanks! I knew there had to be something.
Chris Marasti-Georg
2008-11-03 20:24:33
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
2008-11-03 20:25:21
Not the most obvious name.
James McMahon
2008-12-03 14:23:48
it depends. You are trying to perform an Invalid Operation after all, but there are many ways to name it.
Michael Stum
2008-12-03 15:08:32
+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
2008-11-03 20:26:33
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
2008-11-03 20:29:21
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
2008-11-03 20:31:38
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
2008-11-03 20:59:17
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
2008-11-03 21:08:32
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
2008-11-04 08:55:52