try-finally방식

static String firstLineOfFile(String path) throws IOException{
try(BufferedReader br=new BufferedReader{
new FileReader(path))) {
return br.readLine();
}
}

자원이 2개 이상인 try-finally방식

static void copy(String src,String dst) throws IOException{
InputStream in = new FileInputStream(src);
try{
OutputStream out = new FileOutputStream(dst);
try{
byte[] buf=new byte[BUFFER_SIZE];
int n;
while((n=in.read[buf]>=0))
out.write(buf,0,n);
}finally{
out.close();
}
}finally{
in.close();
}
}
  • try-finally방식은 자원을 회수하는 최선책이 아니며 자원이 둘 이상(try가 2개 이상) 방식은 너무 지저분하다.
  • 기기에 물리적인 오류가 생기면 firstLineOfFile메서드 안의 readline()메서드가 예외를 던지고, 같은 이유로 close메서드도 실패-> 두번째 예외가 첫번째 예외를 완전히 집어상켜버려서 첫번째 예외에 관한 정보를 남기지 않는다.

 

try-with-resources(향상된 예외처리) - 자원을 회수하는 최선책이다  (*try() 코드 블럭이 끝난 뒤 자동으로 자원을 해제(close)해주는 기능)

static String firstLineOfFile(String path) throws IOException{
try (BufferedReader br= new BufferedReader{
new FileReader(Path))){
return br.readLine();
}
}
static void copy(String src, String dst) throws IOException {
  try (InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst)) {
     byte[] buf = new byte[BUFFER_SIZE];
      int n;
      while ((n = in.read[buf] >= 0))
        out.write(buf, 0, n);
  }
}
  • readLine과 close 호출 양쪽에 예외가 발생하면, close에서 발생한 예외는 숨겨지고 readLine에서 발생한 예외가 기록된다. 숨겨진 예외들은 그냥 버려지지않고 스택추적내역에 숨겨졌다는 꼬리표를 달고 출력된다.

try-with-resourcescatch절과 함께 쓰는 모습

static String firstLineOfFile(String path, String defaultVal){
try(BufferReader br=new BufferedREader{
new FileReader(path))){
return br.readLine();
} catch (IOException e){
return defaultVal;
}
}

catch문을 사용해서 try문을 더 중첩하지 않고도 다수의 예외를 처리할 수 있다.

+ Recent posts