-
-
Save donalmurtagh/795984103e639a4aaf2e0fb6a6019c16 to your computer and use it in GitHub Desktop.
int getServerUptime() throws ConnectionException { | |
var server = connect(); | |
server.refresh(); | |
return server.getUptime(); | |
} |
In most cases the right thing to do is to propagate the exception
I disagree. The right thing to do is to handle the exception where it makes sense, and to propagate it where it makes sense. And that depends on the specific semantics of the method invoking the exception-throwing API. There is no silver bullet strategy.
The consensus within the Java community is that checked exceptions were a mistake.
For what is worth, I don't think there is a consensus. And my quarrel is not with checked exceptions, anyway.
The problem Results are trying to solve is twofold:
- As a developer, I want to document what kind of errors my API can fail with. Accordingly, I want to know what kind of errors I should/could be dealing with when I use a third-party API.
- As a developer, I want to be able to use any API with a functional approach, regardless of the types of errors it may fail with.
Checked exceptions meet requirement #1, but the way they are designed in Java makes it hard to use such APIs freely with Function
, Predicate
, Supplier
, Consumer
, and the like. That's why checked exceptions are not a convenient solution for me.
Unchecked exceptions, on the other hand, meet requirement #2. But they remain documented by means of Javadoc only. The compiler will not complain if I neglect the possibility of errors. And that's why unchecked exceptions are not a solution I can rely on, either.
As a beneficial side effect, programs tend to run faster once you remove the overhead of exceptions. All in all, I'm better off using Results than using exceptions.
But if you handle the exception within
getServerUptime
you're preventing callers from handling the error in different ways. In most cases the right thing to do is to propagate the exception, so that (for example) caller A can ignore it and caller B can retry the operationThat's true if the exception is checked. The consensus within the Java community is that checked exceptions were a mistake. For example, all exceptions thrown by the Spring framework are unchecked.