Java

try-with-resources

기존의 Java라고 하면 이제 공부를 하는 입장에서 할말은 아니긴 한거 같지만, 어쨋든 기존의 코드들을 보면 대부분이 try - catch 문에서 자원을 해제하느라 소스가 지저분해 지는 경향이 있다고 생각한다. 이클립스가 경고를 띄워주긴 하지만 가독성이 떨어지는 편이긴하다.


JDK 1.7 version 부터 try - with - resources 문법이 등장하여 코드가 더욱 간결해졌다. 시중의 많은 서적들이 (JDK구버전을 기준으로 쓰여진 책이 많기때문에) try-catch문만 소개하고 있다. 두 문법의 코드를 비교해보겠다.



try - catch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.*;
 
class DataInputStreamEx2{
  public static void main(String[] args){
    int sum = 0;
    int score = 0;
 
    FileInputStream fis = null;
    DataInputStream dis = null;
 
    try{
      fis = new FileInputStream("score.dat");
      dis = new DataInputStream(fis);
 
      while(true){
        score = dis.readInt();
        System.out.println(score);
        sum += score;
      }
    }catch(EOFException e){
      System.out.println("점수의 총합은 "+sum+"입니다.");
    }catch(IOException e){
      e.printStackTrace();
    }finally{
      try{
        if(dis!=null) dis.close();
      }catch(IOException e){
        e.printStackTrace();
      }
    }
  }
}
 
cs



try-with-resources


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;
 
class DataInputStreamEx3{
  public static void main(String[] args){
    int sum = 0;
    int score = 0;
 
    try(DataInputStream dis = new DataInputStream(new FileInputStream("score.dat"))){
      while(true){
        score = dis.readInt();
        System.out.println(score);
        sum += score;
      }
    }catch (EOFException e){
      System.out.println("점수의 총합은 "+sum+"입니다.");
    }catch(IOException e){
      e.printStackTrace();
    }
  }
}
 

cs



자원해제를 해주지 않아도 (close()메서드 호출) 종료가 된다.