수행하려는 일과 관련 없어 보이는 예외가 튀어나오면 당황스러울 것이다. 메서드가 저수준 예외를 처리하지 않고 바깥으로 전파해버릴 때 종종 일어나는 일이다.
이는 내부 구현 방식을 드러내어 윗 레벨 API를 오염시킨다.
구현 방식을 바꾸면 다른 예외가 튀어나와 기존 클라이언트 프로그램을 깨지게 할 수도 있는 것이다.
이러한 문제를 피하려면 상위 계층에서는 저수준 예외를 잡아 자신의 추상화 수준에 맞는 예외로 바꿔 던져줘야 한다.
이를 예외번역(exception translation)
이라고 한다.
try{
...
} catch (LowerLevelException e) {
throw new HigherLevelException("...");
}
public abstract class AbstractSequentialList<E> extends AbstractList<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())
*/
public E get(int index) {
try {
return listIterator(index).next();
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: " + index);
}
}
}
위 두가지 코드가 예외번역의 예시이다.
예외를 번역할 때 저수준 예외가 디버깅에 도움이 된다면 예외 연쇄(exception chaining)
를 사용하는 게 좋다.
// exception chaining 예시
try{
...
} catch (LowerLevelException e) {
throw new HigherLevelException(e);
}