7 ms·
> Don't rethrow the same exception. Handle it. It you want to handle it by throwing another internal unchecked exception, that's fine- No, that's not fine. Typ
by groestl 8y ago
> Don't rethrow the same exception. Handle it. It you want to handle it by throwing another internal unchecked exception, that's fine-
No, that's not fine. Typically, the layer immediately wrapping the throwing code has no knowledge about semantics. It's measurement code, logging code, caching code, transaction handling code, batch explode/aggregation code etc, but nothing that could make sense of a FileNotFoundException. The layer that wraps all this infrastructure code has more info, and can make sense of individual exceptions. By wrapping the original exception, this code now has to go on a getCause() safari to find out what happened. And yes, with checked exceptions there is no way around that, and that's the reason they should go.
- mabbo 8y agoI don't mean to wrap it in a generic exception, I mean to wrap it in a context-specific exception written for the purpose. A "UserDoesntExistException", or a "DatabaseNotRespondingException". Something for the purpose that likely exists in a useful hierarchy.
- groestl 8y agoThis is better, but it could have been the original exception all along, given the rare number of cases in real-world code where the call site actually knows how to recover.
- skybrian 8y agoTypically you don't need to catch at this level of granularity. A generic UnavailableException would cover it. The reasons why a method can fail vary by implementation and you typically don't need to expose this at the API level. It shouldn't be a breaking change for a method to fail for a different reason because the implementation changed. If you take this approach, there are two kinds of methods: those that always succeed and those that can fail. It's similar to how Go's error type works. Java is a mess not due to the existence of checked exceptions, but because they created an unfortunate exception hierarchy and that resulted in inconsistent API design where there's no consensus about what to do.