You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
아래 계층의 예외 처리가 어렵고, 그 예외를 상위 계층을 통해 노출한다면 예외 번역을 사용하라.
예외 연쇄를 이용하면 상위 계층에는 맥락에 어울리는 고수준 예외를 던지면서 근본 원인도 함께 알려주어 오류 분석에 도움이 된다.
예외 번역? 예외 연쇄?
1. 잘못 처리된 예외
메서드가 저수준 예외를 처리하지 않고, 바깥으로 전파하는 경우 (발생 위치에서 예외 처리하지 않는 경우를 말함) 에 대한 문제 발생
수행하려는 일과 관련없는 예외가 발생할 수있다.
구현 방식을 바꾸면 또 다른 예외를 발생시켜 기존 클라이언트 프로그램을 깨뜨릴 수 있다.
2. 예외 번역(Exception Translation)
위와 같은 상황에서의 해결책으로 제시 될 수 있는 방법이다.
상위 계층에서는 저수준 예외를 잡아 자신의 추상화 수준에 맞는 예외로 바꿔 던져야 한다.
publicabstractclassAbstractSequentialList<E> extendsAbstractList<E> {
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= size()) */publicEget(intindex) {
try {
returnlistIterator(index).next();
} catch (NoSuchElementExceptionexc) {
thrownewIndexOutOfBoundsException("Index: "+index);
}
}
}
예외 번역시 저수준 예외가 디버깅에 도움이 된다면 예외 연쇄(exception chanining)을 사용하는게 좋다.
3. 예외 연쇄(exception chanining)
문제의 근본 원인(cause)인 저수준 예외를 고수준 예외에 실어 보내는 방식이다.
예외 연쇄라는 용어를 보다 더 쉽게 이해하기에 좋은 방법은 상승이라는 키워드를 생각 해 보는게 좋을것 같다.
저수준 -> 고수준
보다 더 추상화된 클래스에서의 예외 처리등을 키워드로 잡을 수 있다.
별도의 접근자 메서드(Throwable 의 getCause()) 를 통해 필요하다면 언제든 저수준 예외를 꺼내 볼 수 있다.
Activity