3 ms·
Checked exceptions are one of biggest mistakes Java ever made. That said, patching compiler is not something I would do. What I usually do is add unchecked ex
by vbezhenar 3y ago
Checked exceptions are one of biggest mistakes Java ever made.
That said, patching compiler is not something I would do.
What I usually do is add unchecked exception class for every checked exception I had to "handle". So I have UncheckedIOException from standard library (handy!), UncheckedSQLException and so on and so on.
Yes, it causes more code, but Java is not exactly known for brevity, so be it. At least that way is not hacky in any way and actually used by Java standard library itself, so I'd consider it "idiomatic".
- rogerkeays 3y agoYou can also rethrow checked exceptions as runtime exceptions by exploiting type erasure: public static RuntimeException unchecked(Exception e) { Exceptions.<RuntimeException>throw_checked(e); return null; } private static <E extends Exception> void throw_checked(Exception e) throws E { throw (E) e; } then you can do this: try { ... } catch (IOException e) { throw unchecked(e); } And the original exception is thrown without being wrapped. It's as though you had `throws IOException` on your method signature. This is from my original solution to the problem: https://github.com/rogerkeays/jamaica-core/blob/0cc98b114998dc80bdc3ad26f6678e6eee0a239e/src/exceptions.java#L159C5-L165C2 https://github.com/rogerkeays/jamaica-core/blob/0cc98b114998...
- vbezhenar 3y agoThere's one big problem with this approach. You can't catch checked exception if the try-block does not throw it (according to compiler). That's compiler error. So yes, you can throw IOException masking it to RuntimeException, however you can't catch it later without another gimmicks like catching Exception and checking if it's IOException (and even that check causes linter warnings in Idea, so now you need to suppress those warnings...). Throwing and catching UncheckedIOException does not have this problem.
- rogerkeays 3y agoGood point. Actually the plugin didn't handle this case either (fixed now). Thanks for the feedback.