3 ms·
The greatest secret of exceptions is that in most cases you don't need to catch them. What should really be on your fingertips is try { ... something
by PaulHoule 4y ago
The greatest secret of exceptions is that in most cases you don't need to catch them. What should really be on your fingertips is
try {
... something ...
} finally {
... clean up ...
}
this (plus try-with-resources) is the genius of exceptions. The tragedy of exceptions in Java is that checked exceptions convert the above to
try {
... something ...
} catch(ACheckedExceptionThatHasNothingToDoWithThisCode x) {
throw new SomeOtherCheckedExceptionToPleaseTheCompiler(x)
} finally {
... do what has to be done ...
}
with the variations of
throw new AnUncheckedExceptionSoIDontVandalizeMyCodeMore(x)
and
catch(...) {
// i forgot to rethrow the exception but at least the compiler isn't complaining
}
as well as
// i forgot to add a finally cause because I was writing meaningless catch clauses
As much as I think checked exceptions are a mistake in Java, it is not hard to make up your mind about rethrows and apply them in a checked or unchecked form with little or no thought.
The unhappy path that you get for free with exceptions is correct for code with ordinary control flow. Most of the code has no global view of the application and is no position to handle errors. On the other hand, for many simple programs, the correct behavior is "abort the program, clean up resources, display an error message" which a sane exception system gives you for free (except for the finally which cleans up the happy path too)
For a complex control flow there is something high up in the call stack that has global responsibility. Imagine a webcrawler which is coordinating multiple threads that call fetchUrl(url) fetchUrl doesn't need to catch exceptions at all, just clean up with finally. What it may need to do is tag exceptions with contextual information that will help the coordinator make decisions. That webcrawler in particular will deal with intermittent failures all the time and only the coordinator is in a position to decide if it wants to retry and on one schedule.