본문 바로가기

Java

[Java] try-with-resources 예외처리

너무 늦게 알게된 기능이 있어서 일단 따라 쳐보고 습득해야할 것이다.

 

말로 설명하자면, try 옆 () 속에 리소스가 있으면  try 블록 끝나고 자동을 종료해주는 기능이라고한다.

(Exception이 되어도 close()가 보장됨)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) {
     
    BufferedReader br = null;
 
    try {
        String str;
        br = new BufferedReader(new FileReader("C:\\number.txt"));
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
cs

위 코드가 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
    try (BufferedReader br = new BufferedReader(new FileReader("C:\\number.txt"))) {
        String str;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
cs

이렇게 간편해 진다고 합니다. 

 

출처: http://stackoverflow.com/questions/17650970/am-i-using-the-java-7-try-with-resources-correctly