Open tonykang22 opened 2 years ago
자원이 둘 이상이라면 try-finally 방식은 너무 지저분하게 된다.
예외를 잡아먹지 않는다
또한 try-with-resources를 사용하면서 catch, finally도 모두 사용이 가능하다. 그렇기 때문에 단점 없이 단점만 있다고 판단.
public class Copy { private static final int BUFFER_SIZE = 8 * 1024; 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(); } } public static void main(String[] args) throws IOException { String src = args[0]; String dst = args[1]; copy(src, dst); } }
public class Copy { private static final int BUFFER_SIZE = 8 * 1024; 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); } } public static void main(String[] args) throws IOException { String src = args[0]; String dst = args[1]; copy(src, dst); } }
주석 참고 (finally 안에서 다시 try-catch로 마치 자원을 안전하게 회수하는 듯 코드 작성)
발생하는 예외가 IOException이 아니라 다른 예외라면 문제가 발생한다.
public class Copy { private static final int BUFFER_SIZE = 8 * 1024;
static void copy(String src, String dst) throws IOException { InputStream in = new FileInputStream(src); 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 { try { out.close(); } catch (IOException e) { // TODO 이렇게 하면 되는거 아닌가? }
try { in.close(); } catch (IOException e) { // TODO 안전한가? } }
}
public static void main(String[] args) throws IOException { String src = args[0]; String dst = args[1]; copy(src, dst); } }
어떻게 close()가 호출이 되며, 어떻게 첫 번째 예외도 호출이 될까?
addSuppressed()
close()
아이템 9. try-finally 보다 try-with-resources를 사용하라.
핵심 정리
예시 코드
자원이 둘 이상이라면 try-finally 방식은 너무 지저분하게 된다.
예외를 잡아먹지 않는다
는 것이다.또한 try-with-resources를 사용하면서 catch, finally도 모두 사용이 가능하다. 그렇기 때문에 단점 없이 단점만 있다고 판단.
완벽 공략
예시 코드 (자바 퍼즐러 예외 처리 코드의 실수)
주석 참고 (finally 안에서 다시 try-catch로 마치 자원을 안전하게 회수하는 듯 코드 작성)
발생하는 예외가 IOException이 아니라 다른 예외라면 문제가 발생한다.
static void copy(String src, String dst) throws IOException { InputStream in = new FileInputStream(src); 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 { try { out.close(); } catch (IOException e) { // TODO 이렇게 하면 되는거 아닌가? }
}
public static void main(String[] args) throws IOException { String src = args[0]; String dst = args[1]; copy(src, dst); } }
예시 코드 (try-with-resources 바이트 코드)
어떻게 close()가 호출이 되며, 어떻게 첫 번째 예외도 호출이 될까?
addSuppressed()
로 예외를 추가하도록 한다.close()
를 여러번 호출할 수도 있기 때문에 멱등성이 보장되어야 한다.