사용자 도구

사이트 도구


java:exception

문서의 이전 판입니다!


Java Exception

Checked Exception

가능하면 사용하지 말 것.

  • Throwing Undeclared Checked Exceptions | Javalobby
    class Thrower {
        public static void spit(final Throwable exception) {
            class EvilThrower<T extends Throwable> {
                @SuppressWarnings("unchecked")
                private void sneakyThrow(Throwable exception) throws T {
                    throw (T) exception;
                }
            }
            new EvilThrower<RuntimeException>().sneakyThrow(exception);
        }
    }
     
    public class ThrowerSample {
        public static void main( String[] args ) {
            Thrower.spit(new RemoteException("go unchecked!"));
        }
    }
  • Throwing Checked Exceptions Like Unchecked Exceptions in Java | Gamlor
    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;
        }
    }
java/exception.1390363565.txt.gz · 마지막으로 수정됨: 2014/01/22 13:06 저자 kwon37xi