|
Re: What's Your ShouldNeverHappenException?
|
Posted: Jan 16, 2007 3:26 PM
|
|
> In my view, an assertion verifies a property so important > that if violated the program can no longer carry on. For > example, if I have an internal method in my software that > should never ever (ever!) receive a null argument, I'd > like to verify it with an assertion. This isn't a runtime > exception, this is an error in the way I have designed my > code. If I've turned assertions off, then the state of my > program is effectively random, who knows what is going to > happen? I would rather exit quickly in a known way, than > hope that my "should never happen" event isn't going to > cause the world to end. From "The Pragmatic Programmer", > "dead programs tell no lies". As an example, if I'm > writing a tree algorithm, I might make the assertion that > each node has one parent. If this is violated, none of my > tree algorithms will make any sense. > Java has a different approach to checking pre-conditions than Eiffel. Eiffel uses assertions. What I do in Java, which is the accepted approach I think, is check with Java code and throw semantically meaningful runtime exceptions: NullPointerException , IllegalArgumentException , etc. This is a fail-fast strategy. It just doesn't use assertions or throw AssertionError .
Also, checking of preconditions won't generate what I call should-never-happen exceptions. Should-never-happen exceptions is the category of exceptions that I'm forced to catch in Java because they are checked, but I really don't think they will every be thrown. In any other language, I wouldn't catch them in the first place, because I wouldn't be forced to do so by the compiler.
|
|