- 아래 출처를 통해 작성한 글입니다.
- 개인 공부 목적으로 작성한 글입니다.
1. try-finally
static String firstLineOfFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}
2. try-with-resources
- 이 구조를 사용하려면 해당 자원이
AutoCloseable
인터페이스를 구현해야 합니다.
AutoCloseable
인터페이스는 단순히 void를 반환하는 close 메서드 하나만 덩그러니 정의한 인터페이스입니다.
static String firstLineOfFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}
- try-with-resources는 문제를 진단하기도 훨씬 수월합니다.
- 숨겨진 예외들도 버려지지 않고 스택 추적 내역에
숨겨졌다(suppressed)
는 꼬리표를 달고 출력됩니다.
2-1. t-w-r with catch
- 아래 코드는 파일을 열거나 데이터를 읽지 못했을 때 예외를 던지는 대신 기본 값을 반환하도록 했습니다.
static String firstLineOfFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
return defaultVal;
}
}
- 출처
- Joshua Bloch, 『EFFECTIVE JAVA 3/E』, 개앞맵시 옮김, 프로그래밍인사이트(2018)