언어&프레임워크/Java

Try with Resource(Exception, close, FileWriter)(java)

밍풀 2022. 9. 8. 08:00

try catch finally 를 사용한 close VS try with resource 를 사용한 close 처리 (똑같이 작동함)

 

try with resource의 사용조건)

클래스가(여기선 FileWriter) autocloseable인터페이스 가지고 있으면 try with resource 문법 사용가능

단, java7이상 부터 사용가능 유의

 

try with resource의 사용법)

try with resource는 try문 다음 소괄호 사용함이 try catch 문과 다른점임.

소괄호에 close 시켜야 하는 부분 넣음(클로즈가 필요한 클래스를 인스턴스화 시키는 코드 넣어)

try문 안에 close 넣지 않음, 필요없음, 자동으로 해주니 중복임 (filewriter 모든 작업 끝나고 나서 자동으로 close 내부적으로 수행해줌)

 

try with resource의 사용성)

리소스와 관련된 작업시 close가 꼭 필요할때는 try with resource 사용하는게 실수를 줄이고 훨씬 간편

 

 

trywithresource 실행해보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.FileWriter;
import java.io.IOException;
 
public class trywithresource {
 
    public static void main(String[] args) {
        try(FileWriter w = new FileWriter("data321.txt")){
            w.write("I get it");
        }catch(IOException e){
            e.printStackTrace();
        }
            
 
    }
 
}
 
cs