import java.io.IOException;
// Don't do this either - circumvents exception checking!
public class Thrower {
private static Throwable t;
private Thrower() throws Throwable {
throw t;
}
public static synchronized void sneakyThrow(Throwable t) {
Thrower.t = t;
try {
Thrower.class.newInstance();
} catch (InstantiationException e) {
throw new IllegalArgumentException();
} catch (IllegalAccessException e) {
throw new IllegalArgumentException();
} finally {
Thrower.t = null; // Avoid memory leak
}
}
public static void main(String[] args) {
System.out.println("Oh I'm so innocent");
IOException exception = new IOException("hehe");
Thrower.sneakyThrow(exception);
}
}
it's the 43 puzzle from the book <<java puzzler>>.
in this solution it can throw checked exception without compile time checking.
but with some limitations when it wants to throw InstantiationException and IllegalAccessException.
reference: http://www.javaspecialists.eu/archive/Issue144.html