How do you handle "impossible" exceptions in Java?
I catch the Exception
and wrap it in an Error
. from the doc of Error
:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
I would skip the funny message.
BTW: I had a case where a piece of code (in a small library) just assumed that an encoding would be available. Only it got deployed on a limited device and exploded at runtime.
Checked exceptions serve to show places in our code where we should pause for a second and consider the paths less traveled (as in "what my app does when network dies" and other corner cases). Wrapping them in IllegalStateException and rethrowing is a sort of a signed contract, where the programmer says: "yes, all risks considered I take full responsibility for the spot right here". If it wasn't for checked exceptions, we would hava no way of knowing a consious decision from a plain lack of thought.
Well, IMHO there is a better way than "log[ging] a funny error regarding how the laws of the universe have changed" because in doing so you are "being cute," which among friends is fine but is not universally (no pun intended) accepted. Your code may be read by others and if your humor falls flat (on them) you haven't really made any friends.
Many style guides make suggestions for impossible exceptions. You can use an empty catch block with the exception parameter being named willNeverHappen
; you can place a comment in the empty block; you can throw a runtime exception (probably the best, since you MIGHT misspell UTF-8!)
If you want to be super ambitious, you can write an annotation, like SneakyThrows in Lombok. Whether you would consider this "better" is simply a matter of taste. :)
Note that this question was discussed on https://softwareengineering.stackexchange.com/questions/122233/how-to-deal-with-checked-exceptions-that-cannot-ever-be-thrown.