Guava : Throwables

13809 단어 JavaJava

1. 메소드 목록

리턴 타입 메소드 설명
static List<Throwable> getCausalChain(Throwable throwable) throwable의 원인 사슬을 목록으로 반환한다.
static <X extends Throwable> X getCauseAs(Throwable throwable, Class<X> expectedCauseType) expectedCauseType으로 변환해 throwable의 원인을 반환한다.
static Throwable getRootCause(Throwable throwable) throwable의 루트 원인을 반환한다.
static String getStackTraceAsString(Throwable throwable) throwable의 원인 스택 트레이스를 toString()을 사용해 문자열로 반환한다.
static <X extends Throwable> void propagateIfPossible(Throwable throwable, Class<X> declaredType) 정확히 RuntimeException, Error나 declaredType의 인스턴스인 경우에만 예외를 전파한다.
static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) 정확히 RuntimeException, Error나 declaredType1, declaredType2의 인스턴스인 경우에만 예외를 전파한다.
static <X extends Throwable> void throwIfInstanceOf(Throwable throwable, Class<X> declaredType) declaredType의 인스턴스인 경우에만 throwable을 던진다
static void throwIfUnchecked(Throwable throwable) RuntimeException이나 Error의 경우에만 throwable을 던진다.

2. 메소드 설명

1. throwIfInstanceOf : declaredType의 인스턴스인 경우에만 throwable을 던진다

 for (Foo foo : foos) {
   try {
     foo.bar();
   } catch (BarException | RuntimeException | Error t) {
     failure = t;
   }
 }
 if (failure != null) {
   throwIfInstanceOf(failure, BarException.class);
   throwIfUnchecked(failure);
   throw new AssertionError(failure);
 }

2. throwIfUnchecked : RuntimeException이나 Error의 경우에만 throwable을 던진다.

 for (Foo foo : foos) {
   try {
     foo.bar();
   } catch (RuntimeException | Error t) {
     failure = t;
   }
 }
 if (failure != null) {
   throwIfUnchecked(failure);
   throw new AssertionError(failure);
 }

3. propagateIfPossible : 정확히 RuntimeException, Error나 declaredType의 인스턴스인 경우에만 예외를 전파한다.

try {
   someMethodThatCouldThrowAnything();
 } catch (IKnowWhatToDoWithThisException e) {
   handle(e);
 } catch (Throwable t) {
   Throwables.propagateIfPossible(t, OtherException.class);
   throw new RuntimeException("unexpected", t);
 }

3. 동작 원리

public void doSomething() 
    throws IOException, SQLException {

    try {
        someMethodThatCouldThrowAnything();
    } catch (IKnowWhatToDoWithThisException e) {
        handle(e);
    } catch (Throwable t) {
        Throwables.propagateIfInstanceOf(t, IOException.class);
        Throwables.propagateIfInstanceOf(t, SQLException.class);
        throw Throwables.propagate(t);
    }  
}
public void doSomething() 
    throws IOException, SQLException {

    try {
        someMethodThatCouldThrowAnything();
    } catch (IKnowWhatToDoWithThisException e) {
        handle(e);
    } catch (SQLException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }  
}

참고

좋은 웹페이지 즐겨찾기