Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

아이템 77. 예외를 무시하지 말라 #68

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions 10장/아이템_77/예외를_무시하지_말라.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# 아이템 77. 예외를 무시하지 말라

### API 명세에 예외를 괜히 명시하는 게 아니다

- 예외는 적절한 조치를 취해야 한다. (체크 예외, 언체크 예외 둘 다)
- try로 감싸고 catch에서 꼭 무언가를 해야 한다!

```java
// 금지!
try {
...
} catch (SomeException e) {
}
```

- 위 코드는 화재경보를 무시하는 수준을 넘어 화재경보기를 꺼 버리는 행위이다.

### 예외를 무시해야 할 때도 있다

- 예) `FileInputStream`을 닫을 때
- 파일의 상태를 변경하지 않았으니 복구할 것이 없다.
- 필요한 정보는 다 읽었다는 뜻이니 남은 작업을 중단할 이유가 없다.
- 그렇지만 같은 예외가 자주 발생한다면 조사해보는 것이 좋다. 로깅 정도는 해 두자.
- 예외를 무시하기로 했다면 catch 블록 안에 이유를 주석으로 남기고, 예외 변수의 이름을 `ignored`로 바꾸자.

```java
Future<Integer> f = exec.submit(planarMap::chromaticNumber);
int numColors = 4;
try {
numColors = f.get(1L, TimeUnit.SECONDS);
} catch (TimeoutException | ExecutionException ignored) {
// 기본값을 사용한다(색상 수를 최소화하면 좋ㅈ지만, 필수는 아니다).
}
```


# 결론

- 예외를 무시하지 말고 적절히 처리하자. (화재경보기를 끄지 말자.)
- 안 그러면 아무 상관없는 곳에서 갑자기 죽어버릴 수도 있다.
- 빈 catch 블록을 발견하면 의심해 보자.
- 무시하지 않고 바깥으로 전파되게만 놔둬도 최소한 디버깅 정보를 남긴 채 프로그램이 신속히 중단되게는 할 수 있다. (fail-fast)