Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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...



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.


Good point. Actually the plugin didn't handle this case either (fixed now). Thanks for the feedback.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: