문서의 이전 판입니다!
가능하면 사용하지 말 것.
public class ExceptionThrower { private ExceptionThrower() {} public static void spit(final Throwable throwable) { // 아래 <RuntimeException> 타입 정보는 컴파일 상태에서는 지워진다. ExceptionThrower.<RuntimeException>throwWithoutCheck(throwable); } @SuppressWarnings("unchecked") private static <T extends Throwable> void throwWithoutCheck(Throwable throwable) throws T { // 아래 Type Casting 정보는 Java Generic의 특성상 컴파일시 정보가 사라지므로 // 실제 캐스팅은 발생하지 않는다. throw (T) throwable; } } public final class UncheckedThrow { private UncheckedThrow(){} public static void throwUnchecked(final Exception ex){ // Now we use the 'generic' method. Normally the type T is inferred // from the parameters. However you can specify the type also explicit! // Now we du just that! We use the RuntimeException as type! // That means the throwsUnchecked throws an unchecked exception! // Since the types are erased, no type-information is there to prevent this! UncheckedThrow.<RuntimeException>throwsUnchecked(ex); } /** * Remember, Generics are erased in Java. So this basically throws an Exception. The real * Type of T is lost during the compilation */ public static <T extends Exception> void throwsUnchecked(Exception toThrow) throws T{ // Since the type is erased, this cast actually does nothing!!! // we can throw any exception throw (T) toThrow; } }