I work on a project with a legacy service layer that returns null in many places if a requested record does not exist, or cannot be accessed due to the caller not being authorized. I am talking about specific records requested by ID. For instance, something like:
Though I agree with the view that unchecked exceptions make for a more convenient API, that's not to my mind the most important benefit. Instead it's this:
Throwing unchecked exceptions helps you avoid serious bugs.
Here's why. Given ten developers forced to deal with checked exceptions, you are going to get twenty different strategies for dealing with them, many of which are totally inappropriate. Here are some of the more common bad approaches:
IOExceptionbecomes "Can't connect to the server" even if establishing a connection has nothing to do with the issue.
Throwableinstead of the two checked exceptions that the method actually throws. The exception handling code makes no attempt to distinguish (say) resource availability issues (e.g. some
IOExceptions) from outright code errors (e.g.
NullPointerException). Indeed it often picks one of the exceptions arbitrarily and misreports every exception as being of that type.
Throwablebecause there's nothing else that would handle all the exceptions being thrown.
In my experience it is quite a bit more common to see the approaches above than it is to see a correct response. Many developers--even "senior" developers--have this idea that exceptions must be suppressed at all costs, even if it means running the app in an unstable state. That is dangerously wrong.
Unchecked exceptions help avoid this issue. Developers who don't know how to handle exceptions tend to see exceptions as inconveniences to overcome, and they don't go out of their way to catch them. So the exceptions just bubble up to the top where they offer up a stack trace and where they can be handled in a consistent fashion. In the rare case where there's actually something better to do than let the exception bubble up, there's nothing stopping you.