Re: Why shouldn't we catch class RuntimeException?
~kurt wrote:
Ben Schumeth <bens@enfocus.be> wrote:
On Tue, 12 Jun 2007 16:47:17 +0200, <kaja_love160@yahoo.com> wrote:
Hello
Book I?m learning from claims that exceptions of type RuntimeException
and its children are thrown due to bad programming and should be
avoided by writing better code.
Please throw that book out the window, preferably onto the writer's head.
I believe the OP is not understanding that a RuntimeException usually
isn't used for checking IO (that would be an IOException). RuntimeExceptions
are "unchecked" and pretty much always due to a programming error. I can
think of cases where you might want to catch them - but they would still be due
to writing the application wrong.
This seems like an extremely potent argument in favor of catching and logging
such exceptions. A programmer should know when they err.
Alternatively, getInput could do some error checking. Now, if the user
gives invalid input, what should getInput do? It might tell the user that
the input is incorrect and ask new input. Fine, but what if getInput
doesn't know how to show output since that is showOutput's task? (note:
getInput and showOutput could be methods of different classes) getInput
knows how to get input, but it has no idea where output should go, what
format it should have, ... In that case it is perfectly reasonable to
have getInput throw a RuntimeException, and have doSomething catch that
exception and handle it as required.
I think you would want to throw an IOException (checked), not a
RuntimeException. Both are Exceptions, but neither inherits from the
the other.
The question of whether to throw a checked or unchecked Exception is subtle
and controversial. Thee suggestion to throw a RuntimeException for programmer
errors and a checked Exception for data or user errors made sense to me.
In the book's defence, it was probably talking about NullPointerException,
ClassCastException, IllegalArgumentException, etc. which can - in many
cases - indeed be avoided.
These are all RuntimeExceptions.
But they aren't all the RuntimeExceptions.
There are two discussions here - whether to catch RuntimeExceptions and
whether to throw them. I'm in favor of both, under the right circumstances.
--
Lew