사용자 도구

사이트 도구


java:exception

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

다음 판
이전 판
다음 판 양쪽 다음 판
java:exception [2014/01/22 12:58]
kwon37xi 새로 만듦
java:exception [2014/01/22 13:20]
kwon37xi [Checked Exception]
줄 3: 줄 3:
 ===== Checked Exception ===== ===== Checked Exception =====
 가능하면 사용하지 말 것. 가능하면 사용하지 말 것.
-  * [[http://java.dzone.com/articles/throwing-undeclared-checked|Throwing Undeclared Checked Exceptions | Javalobby]]<code java> +  * [[http://java.dzone.com/articles/throwing-undeclared-checked|Throwing Undeclared Checked Exceptions | Javalobby]] 
-class Thrower +  * [[http://www.gamlor.info/wordpress/?p=1020|Throwing Checked Exceptions Like Unchecked Exceptions in Java | Gamlor]]<code java> 
-    public static void spit(final Throwable exception) { +public class ExceptionThrower { 
-        class EvilThrower<T extends Throwable{ +    private ExceptionThrower() {} 
-            @SuppressWarnings("unchecked"+ 
-            private void sneakyThrow(Throwable exception) throws T { +    public static void spit(final Throwable throwable) { 
-                throw (T) exception; +        // 아래 <RuntimeException타입 정보는 컴파일 상태에서는 지워진다. 
-            } +        ExceptionThrower.<RuntimeException>throwWithoutCheck(throwable); 
-        } +    } 
-        new EvilThrower().sneakyThrow(exception);+ 
 +    @SuppressWarnings("unchecked"
 +    private static <T extends Throwable> void throwWithoutCheck(Throwable throwable) throws T { 
 +        // 아래 Type Casting 정보는 Java Generic의 특성상 컴파일시 정보가 사라지므로 
 +        // 실제 캐스팅은 발생하지 않는다. 
 +        throw (Tthrowable;
     }     }
 } }
  
-public class ThrowerSample +public final class UncheckedThrow { 
-    public static void mainString[] args ) { +    private UncheckedThrow(){} 
-        Thrower.spit(new RemoteException("go unchecked!"));+ 
 +    public static void throwUnchecked(final Exception ex){ 
 +        // Now we use the 'generic' methodNormally 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 (TtoThrow;
     }     }
 } }
 </code> </code>
-  * [[http://www.gamlor.info/wordpress/?p=1020|Throwing Checked Exceptions Like Unchecked Exceptions in Java | Gamlor]] 
java/exception.txt · 마지막으로 수정됨: 2021/07/14 12:49 저자 kwon37xi