Item 61. 추상화 수주에 맞는 예외를 던저라.

예외 변환

상위 계층에서는 하위 계층에서 발생하는 예외를 반드시 받아서 상위 계층 추상화 수준에 맞는 예외로 바꿔서 던져야 한다.

위 내용을 요약하면, 상위 계층 추상화에 맞게 변환해서 예외를 던저야 한다. 이 숙어를 예외 변환(exception translation)이라고 한다.

// 예외 변환 (exception translation)
try {
    // 낮은 수준의 추상화 계층
    ...
} catch(LowerLevelException e) {
    throw new HighLevelException(...);
}

예외 연결

/**
 * Returns the element at the specified position in this list.
 * @throws IndexOutOfBoundsException if the index is out of range
 *         ({@code index < 0 || index >= size()}).
 */
 public E get(int index){
     ListIterator<E> i = listIterator(index);
     try{
         return i.next();
     } catch(NoSuchElementException e) {
         throw new IndexOutOfBoundsException("Index: " + index);
     }
 }
// 예외 연결
try {
    // 낮은 수준의 추상화 계층
    ...
} catch(LowerLevelException cause) {
    throw new HighLevelException(cause);
}
// "에외 연결" 지원 생성자를 갖춘 예외
class HighLevelException extends Exception{
    HighLevelException(Throwable cause){
        super(cause);
    }
} 

결론