자바에는 exception이라는 훌륭한 기능을 제공한다.
그중 두가지 exception 종류는 아래와 같은 표로 정리 할 수 있다.
|
checked exception |
unchecked exception |
처리여부 |
반드시 처리 |
명시적으로 처리 안해도 됨 |
확인시점 |
컴파일 |
런타임 |
대표예외 |
exception의 상속받는 하위 클래스 중 Runtime exception을 제외한 모든 예외 |
runtime exception 하위 예외 |
이 중 checked exception을 너무 많이 남발하게 되면 불편하므로 checked exception을 던지지 않는 소스로 리펙토링 하는 것도 좋은 방법이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try{ | |
obj.fileIO(args); | |
}catch(FileInputOutputException e){ | |
//예외사항 처리... | |
... | |
} |
위와 같이 file input output 소스가 있다고 한다면 아래와 같이도 바꿀 수 있을 것이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if(obj.fileIOPermitted(args)){ | |
obj.fileIO(args); | |
}else{ | |
//예외사항 처리... | |
... | |
} |
항상 이렇게 리펙토링 가능한 것은 아니지만 이렇게 한다면 api는 좀 더 사용하기 편리해질 것이다.
하지만 이렇게 쓴다면 오히려 api를 사용하는데 있어 불편할 수도 있을 것 같다.(실수를 할 수도 있을 것 같다.)
try-catch문에서는 강제로 예외처리를 하여 컴파일시에 명시하도록 하지만, 위와 같은 api에서는 if문 안에 있는 method는 강제성이 없기 때문이다.
End of Document
반응형
'개발이야기 > Effective Java' 카테고리의 다른 글
[Effective Java]실패 원자성 달성을 위해 노력하라 (0) | 2017.03.04 |
---|---|
[Effective Java]어떤 오류인지를 드러내는 정보를 상세한 메시지에 담으라 (0) | 2017.03.04 |
[Effective Java]메서드에서 던져지는 모든 예외에 대해 문서를 남겨라 (0) | 2017.03.04 |
[Effective Java]표준 예외를 사용하라 (0) | 2017.03.04 |
[Effective Java]예외는 예외적 상황에만 사용하라 (0) | 2017.02.22 |
[Effective Java]생성자 인자가 많을 때는 Builder 패턴 적용을 고려하라. (1) | 2017.02.20 |