In Java language (source code) you can't throw checked exceptions if method doesn't declare that.
Typical solution is to wrap it into RuntimeException
, but this way you hide exception type.
There are big production projects that have a method that wrap exception into RuntimeException
to avoid declaring checked exceptions in methods:
- RxJava 2.x ExceptionHelper.wrapOrThrow
- Guava Throwables.propagate, they even deprecated it and propose manual wrapping into
RuntimeException()
Throw checked Exception
s and Throwable
s without wrapping and without declaring it in method description.
From Java bytecode and JVM POV it's totally ok to throw checked exceptions anywhere, see ATHROW
opcode documentation.
The only problem is that you can't write Java code that does this because Java compiler won't let you compile it…
So I codegen bytecode that does it with ASM and then create a jar!
Library has 0 dependencies, targets Java 6 and provides a single static method:
UncheckExceptions.thr0w(Throwable t);
I highly recommend statically import thr0w
method, so it'll look like standard throw
:
import static com.artemzin.uncheckexceptions.UncheckExceptions.thr0w;
public static void main(String[] args) { // Note that it doesn't declare `throws Exception`!
thr0w(new Exception());
}
I haven't published it to Maven Central yet (hopefully will do soon, Gradle publishing is ridiculous).
However you can download jar to play with from Releases page.
- "Sneaky Throw" (just google that), it's a trick with Java generics that lets you do it from Java code. Example in Okio
- Lombok's
@SneakyThrows
feature allows you do just that, but requires to use Lombok (duh). - Kotlin lets you throw any exceptions as unchecked, but requires to use Kotlin (duh). It's a great alternative though, but there are foundational projects like RxJava that can't use Kotlin
Project has two modules:
uncheck-exceptions-codegen
generates bytecode that can throw checked exception as unchecked (has unit tests).uncheck-exceptions-integration-test
consumes generateduncheck-exceptions.jar
and runs integration tests to make sure library works as expected.
To build project you need Bash and JDK 7+, then run:
ci/build.sh
It'll output something like:
…
Done!
uncheck-exceptions.jar can be found in build/libs directory.
You can import project in IntelliJ or your JVM IDE of choice.
Note:
uncheck-exceptions-integration-test
might be red in IDE until you runci/build.sh
because it links to jar that needs to be generated first. PRs to wire it properly via Gradle is very welcome!