3 ms·
You are indeed right, and this is a nuisance. But there is a "correct" solution imho, which is to write: try { .... } catch (IOException e
by adrianmsmith 6y ago
You are indeed right, and this is a nuisance. But there is a "correct" solution imho, which is to write:
try {
....
}
catch (IOException e) { throw new RuntimeException(e); }
It asserts "I believe this error can never happen - so if it does, just re-raise it and it'll get to the top level and the request or program will terminate - which isn't a problem, as, as I've said, this can never happen".
As we all know here, sometimes things that can never happen do happen e.g., as you stated, you initially wrote the program knowing it took a stream based on a string, but later that got changed to something that reads from a network. Having that error raised and logged top-level is the ideal outcome if such a mistake is made.
This syntax is verbose and I do wish there were a better syntax (e.g. Lombok @SneakyThrows is a hack which improves the situation somewhat) but the approach is the correct one.
And it also shows that you've thought about the exception. I even often find myself putting a little comment, mainly meant for future developers reading the code to whom it might not be obvious why this could never happen:
// Can never happen: Stream is always a string
catch (IOException e) { throw new RuntimeException(e); }
- AnimalMuppet 6y agoAlmost. The right answer is to throw new JsonParseException(e) instead. That says that yes, this exception can happen, it's a JSON parse error. But the "outer" exception stack trace will lead to this catch block, which doesn't give all the information. But the exception wraps the "inner" exception, which has the stack trace to where the actual problem was detected. But the inner exception had the wrong type (IOException), so you wrap it with the outer exception to correctly convey what went wrong.
- vips7L 6y agoThrowing RuntimeException is never correct. throw new UncheckedIOException(ex);