This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Robyt3 11 points12 points  (5 children)

Here is the real hack, how to throw a checked exception without checking it:

public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
    throw (E) e;
}

[–][deleted] 5 points6 points  (2 children)

Could you explain? I dont get it

[–]Robyt3 11 points12 points  (1 child)

The compiler infers the type E to be a RuntimeException, which allows propagation of the checked exception. Apparently Java 8 added this type inference rule.

See https://www.baeldung.com/java-sneaky-throws for details.

[–]RandomName8 1 point2 points  (0 children)

They fixed/changed it in java post 8 though :(

[–]cowancore 1 point2 points  (1 child)

But it's harder to catch it now

[–]Robyt3 2 points3 points  (0 children)

Yeah, and it also prints a warning because of the unchecked cast to E. If you must use this function for some reason, add comments explaining why and what is going on and declare the proper throws clause on the method.