Java Best Practices – Handling Runtime Exceptions in Code

exceptionsjava

I am working on a Java application, and I see that Run time exceptions are handled in many places. For example,

try {
    // do something
} catch(NullPointerException e) {
    return null;
}

My questions is, when is it a good practice to handle Runtime exceptions? When should exceptions be left unhandled?

Best Answer

It depends.

For example, Integer#parseInt throws NumberFormatException (which is a RTE) if the provided string can't be parsed. But surely you don't want your app to crash just because the user wrote "x" to a text field that was for integers? And how do you know whether the string can be parsed, unless you try to parse it first? So in this case, the RTE is just an error signal that should cause some kind of error message. One could argue that it should be a checked exception, but what can you do - it isn't.