Checked vs Unchecked Exceptions in Java

CheckedException needs to be handled by the caller, Unchecked exception don’t.

So, when you design your application you should take in mind what kind of exceptional situation you are managing.

For example, if you design a validation method that checks the validity of some user input, then you know that the caller must check the validation exception and display the errors to the user in a nice looking way. This should be a checked exception.

Or, for those exceptional conditions that can be recovered: imagine you have a load balancer and you want notify the caller that one of the “n” servers is down, so the caller must recover the incident re-routing the message to another server; this should be a checked exception, because it is crucial that the caller (client) tries to recover the error, and don’t just let the error to break the program flow.

Instead, there are many conditions that should not happen, and/or should instead break the program. For example, a programming error (like division by zero, null pointer exception), a wrong usage of an API (IllegalStateException, OperationNotSupportedException), an hardware crash, or just some minor situation that are not recoverable (lost connection to a server), or a doomsday 🙂 ; in those cases, the normal handling is to let the exception reach the most outer block of your code that displays to the user that an unpredictable error has occurred and the application can’t do nothing to continue. It’s a a fatal condition, so the only thing you can do is to print it to the logs or showing it to the user in the user interface. In those cases, catching the exception is wrong, because, after catching the exception you need to manually stop the program to avoid further damages; so it could be better to let some kind of exception “hit the fan” 🙂

For those reasons there are some exceptions that are Unchecked also in the JRE: OutOfMemoryError (unrecoverable), NullPointerException (it’s a bug that needs to be fixed), ArrayIndexOutOfBoundsException (another bug example), and so on.

I personally think that also SQLException should be unchecked, since it denotes a bug in the program, or a connection problem to the database. But there are many examples where you get exception that you really don’t have any clue in how to manage (RemoteException).

The best way to handle exceptions are: if you can recover or manage the exception, handle it. Otherwise let the exception pass out; somebody else will need to handle. If you are the last “somebody else” and you don’t know how to handle an exception, just display it (log or display in the UI).

Leave a Comment