Daniel Lubarov

Unsafe exception throwing in Java

Suppose we want to throw an IOException from a Runnable, whose run method declares no exceptions. We can't simply cast it, as in

public static void unsafeThrow(Throwable throwable) {
  throw (RuntimeException) throwable;
}

as cast will fail at runtime. We can get around this by abusing unchecked casts to generic types, though. Here's how:

class UnsafeThrowExample {
  public static void main(String[] args) {
    unsafeThrow(new InterruptedException("wtf?"));
  }

  public static void unsafeThrow(Throwable throwable) {
    UnsafeThrowExample.<RuntimeException>unsafeThrowHelper(throwable);
  }

  @SuppressWarnings("unchecked")
  private static <B extends Throwable> void unsafeThrowHelper(Throwable a) throws B {
    throw (B) a;
  }
}

When we compile and run this, we get:

$ javac UnsafeThrowExample.java && java UnsafeThrowExample
Exception in thread "main" java.lang.InterruptedException: wtf?
	at UnsafeThrowExample.main(UnsafeThrowExample.java:3)

We just threw an InterruptedException from a method which didn't declare any exceptions! I wouldn't suggest using this in production code, but it's a neat trick.