Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it OK to catch a RuntimeException

On a recent project I recommended catching a RuntimeException within a test harness code and logging it. The code processes a series of inputs from a database, and I do not want the test to stop due to failure of any one input (Null values, Illegal arguments, etc.). Needless to say, my suggestion triggered a passionate discussion.

Is catching any kind of RuntimeException acceptable? If yes, what are other scenarios where it is OK to catch RuntimeExceptions?

like image 850
VDev Avatar asked Dec 30 '09 21:12

VDev


People also ask

Is it OK to catch runtime exception?

Catching Exception will catch both checked and runtime exceptions. Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them.

When should I use RuntimeException?

RuntimeException is used for errors when your application can not recover. For example, NullPointerException and ArrayOutOfBoundsException. You can avoid a RuntimeException with an 'if' command. You should not handle or catch it.

What happens if a RuntimeException is never caught and handled?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.

Why runtime exceptions are not checked?

Because the Java programming language does not require methods to catch or to specify runtime exceptions or errors, programmers can be tempted to write code that throws only runtime exceptions or to make all their exception subclasses inherit from RuntimeException .


2 Answers

You catch RuntimeException for the same reason that you catch any exception: You plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to re-throw with a different exception type.

Catching and ignoring any exception, however, is extremely bad practice.

like image 84
kdgregory Avatar answered Oct 13 '22 00:10

kdgregory


Unless you can correct a RuntimeException, you don't want to catch it...

...only true from a developers point of view....

you have to catch all exceptions before they reach up to the UI and make your user sad. This means on the "highest level" you want to catch anything that happend further down. Then you can let the user know there was a problem and at the same time take measures to inform the developers, like sending out alarm mails or whatever...

It is basically considered a data/programming error that could not be forseen, thus you want to improve future releases of the software while at the same time take the user by the hand and move on in a controlled manner...

like image 42
raoulsson Avatar answered Oct 13 '22 00:10

raoulsson