зеркало из
https://github.com/iharh/notes.git
synced 2025-10-29 20:56:06 +02:00
34 строки
1.4 KiB
Plaintext
34 строки
1.4 KiB
Plaintext
Well, there’s one exception to the rule (pun intended). You can take advantage of a change in Java’s 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
|