3 ms·
I don't typically find much value in an exception, checked or unchecked, that is passed up the chain more than one step. The ability to intelligently handle an
by Joeri 10y ago
I don't typically find much value in an exception, checked or unchecked, that is passed up the chain more than one step. The ability to intelligently handle an exception other than by logging/swallowing it decreases very quickly with every step up the call chain. If I don't know what to do with an exception in a particular method it is highly unlikely the caller of that method will have more of a clue.
That's why I tend to catch all exceptions and then either produce a fallback value, or signal back to the caller by returning an Optional (if the only useful thing to tell it is that it wasn't possible to produce a value) or by throwing a new specifically tailored exception and making that checked. In either case, the caller must be explicit about what they want to do when things go wrong.
- ivan_gammel 10y agoThere are few specific cases, when you actually can do something after multiple returns, and they belong to RuntimeException hierarchy. I've seen good example of it just few hours ago, when my IntelliJ WebStorm (Java application) signalled, that it doesn't have enough memory (OoME) and suggested to update Xmx config setting and restart. Apparently, such exceptions should be handled at the root of execution stack, but sometimes, like in this case, there are ways to handle them with minimal damage.
- voodootrucker 10y agoThat's why you allocate every resource in a try-with-resources block, and let the exception fly all the way up to the top level of the stack, where you log it. Everything is unwound, everything is safe, special logic and wrapping not required (though wrapping can be valuable if there is information to add along the way).