반응형
최근엔 Java를 자주 개발하지 않지만 교육을 들으며, 알아두면 좋을 것 같은 문법을 발견하여 기록해둔다.
평소에 자원을 활용하는 코드를 작성할 때엔 무조건 try-catch-finally 문으로 마지막에 close() 를 해주는게 당연하다고 생각했는데, try-with-resources 구문을 활용하면 try문이 종료될 때 자동으로 자원을 종료해주니 코드도 간결해지고 가독성도 좋아질 것 같다는 생각이 들었다. 기억해두었다가 추후 개발을 하게 되면 활용해야겠다.
설명
try-with-resources이란?
- try에 자원 객체를 전달하면, try 코드 블록이 끝나면 자동으로 자원을 종료해주는 기능
- Java7부터 추가된 기능
- AutoCloseable 인터페이스를 구현하고 있는 자원에 대해서만 지원
try-catch-finally로 close 처리를 해줬을 때의 단점
- 자원 반납에 의해 코드가 복잡해짐
- 작업이 번거로움
- 실수로 자원을 반납하지 못하는 경우 발생
- 에러로 자원을 반납하지 못하는 경우 발생
- 에러 스택 트레이스가 누락되어 디버깅이 어려움
try-catch-finally 예시
public static void main(String args[]) throws IOException {
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream("file.txt");
bis = new BufferedInputStream(is);
int data = -1;
while((data = bis.read()) != -1){
System.out.print((char) data);
}
} finally {
// close resources
if (is != null) is.close();
if (bis != null) bis.close();
}
}
try-with-resources 예시
public static void main(String args[]) throws IOException {
try (FileInputStream is = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(is)) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
}
}
[참고]
- Try-with-resources를 이용한 자원해제 처리 (https://ryan-han.com/post/java/try_with_resources/)
- [MangKyu's Diary:티스토리] [Java] try-with-resources란? try-with-resources 사용법 예시와 try-with-resources를 사용해야 하는 이유 (https://mangkyu.tistory.com/217)
반응형
'Develops > JAVA' 카테고리의 다른 글
[JAVA] 변수명 표기법 정리 (카멜, 파스칼, 스네이크, 케밥, 헝가리안) (0) | 2024.05.18 |
---|---|
[JAVA] 자바 로깅 비교 (Logger, Log4j, SLF4J, Logback, Log4j2) (0) | 2024.03.30 |
[JAVA] Lombok 활용하기(Annotation을 활용한 Getter, Setter 처리) (0) | 2024.03.30 |
[JAVA] 문자열 Byte로 자르기 (0) | 2024.03.03 |