📘 Effective Java
[Item 9] try-finally보다는 try-with-resources를 사용하라
loose
2022. 9. 3. 00:16
반응형
Stream, DB Connection, File 등 외부 자원을 이용하는 것들은 해당 자원을 쓰고나면 반납하는 차원에서
close(); 명령어를 써줘야 한다.
try-finally 방식
FileInputStream file = null;
try {
file = new FileInputStream("file.txt");
//파일 로직
}finally{
file.close();
}
try-with-resources 방식
try(FileInputStream file = new FileInputStream("file.txt")){
//file 로직
}
자동으로 close 처리를 해준다.
코드가 깔끔해진다는 장점이 있다.
예외 메시지가 더 정확해진다.
close 과정에서 예외가 발생해도 try 블록에서 발생한 예외가 throws 된다.
728x90