Item 61. 추상화 수주에 맞는 예외를 던저라.
예외 변환
상위 계층에서는 하위 계층에서 발생하는 예외를 반드시 받아서 상위 계층 추상화 수준에 맞는 예외로 바꿔서 던져야 한다.
위 내용을 요약하면, 상위 계층 추상화에 맞게 변환해서 예외를 던저야 한다. 이 숙어를 예외 변환(exception translation)이라고 한다.
// 예외 변환 (exception translation)
try {
// 낮은 수준의 추상화 계층
...
} catch(LowerLevelException e) {
throw new HighLevelException(...);
}
예외 연결
- 하위 계층에서 발생한 예외 정보가 상위 계층 예외를 발생시킨 문제를 디버깅하는데 유용할때 사용함.
- 하위 계층 예외(원인(cause))는 상위 계층 예외로 전달되는데, 상위 계층 예외에 있는 접근자 함수(Throwable.getCause)를 호출하면 해당 정보 확인 가능
/**
* 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);
}
}
결론
- 예외 기법을 사용하는 것보다 예외가 발생하지 않도록 막는 것이 더 좋다. 예외도 객체이므로 너무 남용하지 말자.
- 치명적인 수준의 예외인 경우 상위 계층에서 하위 계층 예외를 격리시키고, 꼭 로그를 남겨 추후에 분석하자.