notes/pl/java/libfws/io/err/sneakythrow.txt
Ihar Hancharenka 7049bdd129 m
2023-08-18 19:09:04 +03:00

34 строки
1.4 KiB
Plaintext
Исходник Ответственный История

Этот файл содержит неоднозначные символы Юникода

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Well, theres one exception to the rule (pun intended). You can take advantage of a change in Javas type inference
regarding Generics and Exceptions in Java 8.
In simple terms, if there are no upper or lower bounds on a generic method signature with throws E,
the compiler assumes the type E to be a
RuntimeException.
This allows you to create the following sneakyThrow:
<E extends Throwable> void sneakyThrow(Throwable e) throws E {
throw (E) e;
}
Regardless of the actual type for the argument e, the compiler assumes throws E to be a RuntimeException
and thereby exempts the method from the catch-or-specify requirement.
The compiler might not complain, but this approach is highly problematic.
https://stackoverflow.com/questions/27644361/how-can-i-throw-checked-exceptions-from-inside-java-8-streams
https://projectlombok.org/features/SneakyThrows
https://github.com/rzwitserloot/lombok/issues/1038
https://github.com/mplushnikov/lombok-intellij-plugin/issues/198
https://github.com/rainerhahnekamp/sneakythrow
https://hackernoon.com/announcing-sneakythrow-8b41b07f9201
https://dzone.com/articles/announcing-sneakythrow
lambdas
https://dzone.com/articles/sneakily-throwing-exceptions-in-lambda-expressions
https://stackoverflow.com/questions/27644361/how-can-i-throw-checked-exceptions-from-inside-java-8-streams
2018
https://www.baeldung.com/java-sneaky-throws