Re:Unchecked Java: Say Goodbye to Checked Exceptions Forever
by rogerkeays on Friday July 14, 2023 @12:33AM
(#36719516)
You 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/0cc98b114998...
Re:Unchecked Java: Say Goodbye to Checked Exceptions Forever
by vbezhenar on Friday July 14, 2023 @01:26AM
(#36719822)
There'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.
Re:Unchecked Java: Say Goodbye to Checked Exceptions Forever
by rogerkeays on Friday July 14, 2023 @04:20AM
(#36720895)
Good point. Actually the plugin didn't handle this case either (fixed now). Thanks for the feedback.
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".