Exceptionshard5-8 years

A colleague shows you code that throws a checked `IOException` straight out of a `Runnable.run()` — no wrapping, no `UncheckedIOException` — and it compiles cleanly with no error anywhere. How is that possible, and what does it prove about what "checked" actually means?

It's possible because checked-exception enforcement is entirely javac's doing — the JVM itself has no concept of "checked" at all. The athrow bytecode instruction that actually throws an exception is the same single instruction for every exception, checked or not; there's no flag on it that says "this one needed a throws clause." The trick (the "sneaky throws" technique Lombok's @SneakyThrows is built on) exploits generics erasure: a helper method declares throws T where T is an unconstrained type parameter, and at a call site with nothing pinning T down, javac infers it as RuntimeException — so the method looks, to the compiler, like it throws nothing checked. At run time, erasure has already happened, the cast inside the method is a no-op, and whatever Throwable was actually passed in goes out through the same athrow as anything else — including a genuine checked IOException, flowing straight through a Runnable.run() whose signature the compiler was certain could never see one.

The lesson behind it →
More on Exceptions