-
[Java] try-catch와 try-with-recourcesJava 2022. 3. 13. 00:01
try-with-resources는 try(...)에서 선언된 객체들에 대해서 try가 종류 될 때 자동으로 자원을 해제해주는 기능입니다.
try에서 선언된 객체가 AutoCloseable 인터페이스를 구현하였다면 Java는 try구문이 종료될 때 객체의 close() 메서드를 호출해 줍니다.
try-catch가 존재했는데 JDK7부터 try-with-resources가 왜 등장했을까요?
Java7 이전에, try-catch-finally 구문으로 자원을 해제하려면 코드의 양도 많고 지저분해집니다.
코드를 통해 설명드려보겠습니다.
다음 코드는 try-catch-finally를 사용하여 문자열 숫자를 입력받아 출력하는 코드입니다.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TryCatch { public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(System.in)); int someValue = Integer.parseInt(br.readLine()); System.out.println(someValue); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Exception을 throws 하지 않고 중첩된 try-catch로 작성된 모습입니다
다음 코드는 try-with-resources를 사용하여 동일한 기능을 하는 코드입니다.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TryCatch { public static void main(String[] args) { // TODO Auto-generated method stub try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in));){ int someValue = Integer.parseInt(br.readLine()); System.out.println(someValue); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
try 문을 벗어나면 try안에서 선언된 객체의 close() 메서드를 호출하기 때문에 finally를 통하여 close()를 명시적으로 호출할 필요가 없습니다.
코드의 depth와 길이가 줄어들고 깔끔해졌습니다.
그러면 모든 객체들을 자동적으로 close() 해줄까요?
모든 객체를 close() 해주지는 않습니다.
AutoCloseable 인터페이스를 구현한 객체에 대해서만 close()가 호출됩니다.
AutoCloseable을 구현하고 있는 클래스들은 다음과 같습니다.
즉, 여기에 존재하는 클래스들은 try-with-resources를 사용했을 때 자동적으로 close() 메서드를 호출합니다.
그러면 우리가 만든 객체에 AutoCloseable을 구현하려면 어떻게 해야 할까요?
AutoCloseable을 implements 해야 합니다.
아래 코드에서 CustomResource 클래스는 AutoCloseable을 구현하였습니다.
main에서는 이 객체를 try-with-resources로 사용하고 있습니다.
public static void main(String args[]) { try (CustomResource cr = new CustomResource()) { cr.doSomething(); } catch (Exception e) { } } private static class CustomResource implements AutoCloseable { public void doSomething() { System.out.println("Do something..."); } @Override public void close() throws Exception { System.out.println("CustomResource.close() is called"); } }
실행해보면 다음과 같이 출력됩니다.
이 예제에서는 close()가 호출될 때 로그를 출력하기 때문에 close()가 실제로 호출되는지 눈으로 확인할 수 있습니다.
Do something... CustomResource.close() is called
출처
https://codechacha.com/ko/java-try-with-resources/
https://docs.oracle.com/javase/9/docs/api/java/lang/AutoCloseable.html
'Java' 카테고리의 다른 글
[Java] 직렬화(Seralize)란? (0) 2022.03.24 [Java] Integer.parseInt() vs Integer.valueOf() (0) 2022.03.20 [Java] Collections.sort () VS Arrays.sort() (0) 2022.03.10 [Java] BufferedWriter vs println 속도분석 (0) 2022.03.04 [Java] Java8 default 인터페이스 (0) 2022.02.28