자원 시도 try에서 리소스를 전달한 후 try 문이 완료된 후 자동으로 리소스를 닫는 기능(auto close)입니다.
이 기능은 Java 7부터 추가되었으며 먼저 다음과 같이 try-catch-finally의 기능을 살펴봅니다.
시도-잡기-마침내
public static void main(String args()) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream("file.txt");
bis = new BufferedInputStream(is);
...
}catch(IOException e){
...
} finally {
// close전 null인지 체크
if (is != null) is.close();
if (bis != null) bis.close();
}
}
이 프로세스에는 다음과 같은 단점이 있습니다.
- 리소스를 실수로 해제하지 않으면 오류가 발생합니다.
- null 여부를 확인한 후 각각을 닫아야 하기 때문에 코드가 복잡합니다.
따라서 Java 7부터는 리소스가 자동으로 닫힙니다. 자원 시도 구문이 추가되었습니다.
자원 시도
public static void main(String args()) throws IOException {
try(FileInputStream fis = new FileInputStream("file.txt")) {
...
}catch(IOException e){
...
}
}
다음과 같이 사용하면 코드가 간결해질 뿐만 아니라 실수로 리소스가 해체되지 않는 오류를 방지할 수 있습니다.
모든 오류에 대한 스택을 남길 수도 있으므로 이와 같은 구문을 사용해야 하는 경우 try-with-resources가 더 유용합니다.
![[Dart] 알고 있으면 좋은 [Dart] 알고 있으면 좋은](https://blog.notus.kr/wp-content/plugins/contextual-related-posts/default.png)