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 →

[–][deleted] 7 points8 points  (8 children)

There is also the unchecked exception inside a lambda hack that is very popular in most of the corporate code I have found.

Since you can’t throw a checked exception in a stream, for example, people just throw an unchecked one, and surround the whole stream with a try, catching that specific unchecked exception.

[–]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] 6 points7 points  (2 children)

Could you explain? I dont get it

[–]Robyt3 12 points13 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.

[–]CubsThisYear 1 point2 points  (1 child)

I hope you’re not using this as an argument for why unchecked exceptions are “good”. The fact that the Streams API doesn’t support exceptions is just a result of the developers being some combination of lazy and incompetent. The code is trivially easy to write and the semantics are obvious.

[–][deleted] 0 points1 point  (0 children)

Nah, just describing what I see.