Re: Which exception to use here?
On Sat, 20 Mar 2010, Christian Schulte wrote:
Stefan Ram schrieb:
[...]
never be thrown in the first place (and if it happens:
indicate a programmer error, not a runtime failure in the
sense of a harddisk device failure or so). So:
What would be a good class to use instead of
?WhatToUseHereException? below?
java.lang.AssertionError probably if the div() method is specified to
_only_ throw the DivisionByZero exception for y == 0 and is never called
with y == 0 in the try block.
Yup. If you believe your code has done what's necessary to get a normal
return out of the submethod, then assert it - put an 'assert false' in the
catch block, or equivalently and better, a 'AssertionError e2 = new
AssertionError("impossible exception happened when dividing");
e2.initCause(e); throw e;'.
THe only trouble with this is that AssertionError is an Error, not a
RuntimeException, so a method which catches and deals with
RuntimeExceptions (eg by showing the user an error message and carrying
on) but not Errors won't deal with it.
If by 'programmer error' you mean an error on the part of the client of
the code you're writing, then an AssertionError isn't appropriate. If
the problem is a bad argument, then there's good old
IllegalArgumentException; if the problem is that your objects haven't been
set up right, then it's IllegalStateException. Other than those two, i
don't think there are any good general-purpose exceptions in the standard
library. Oh, NoSuchElement exception is useful sometimes. And
UnsupportedOperationException, but that's not appropriate here. I think
Mark is right - you probably need to define a new RuntimeException of your
own. Not sure what, though; naming exceptions can be very hard.
tom
--
Change happens with ball-flattening speed. -- Thomas Edison