dracularking 发表于 2013-2-7 17:12:05

circumvents exception checking

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
页: [1]
查看完整版本: circumvents exception checking