이전 포스트에서 에러와 예외를 정리하면서 예외 처리 방법 중 try-catch 문과 try - with - resources 에 대해 자세히 알아보고 싶어 이번 글을 포스팅하고자 합니다.
try - catch 문
try - catch문은 개발자가 예기치못한 예외의 발생에 미리 대처하는 구문으로, 실행중인 프로그램의 비정상적인 종료를 막고, 상태를 정상상태로 유지하는 것이 목적으로 사용합니다.
BufferedReader objReader = null;
try {
// 예외가 발생할 수 있는 코드 작성부
String strCurrentLine;
objReader = new BufferedReader(new FileReader("input.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
System.out.println(strCurrentLine);
} catch (IOException e) {
//IOException 발생시 처리하는 구문
e.printStackTrace();
} finally {
// 정상적인 작동이나 예외 처리 구문 작동 후 마지막으로 후처리 되는 구문
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try - with - resources 문
위 예시와 같이 자원을 사용하고 반납하는 과정에서 불가피하게 사용되는 중복 try-catch 문이나 개발자가 실수로 자원을 반납하지 않는 경우를 방지하기위해 추가된 try - with -resources 문을 살펴보면 try에 자원 객체를 전달하면, try 코드 블록이 끝나면 자동으로 자원을 종료해주는 기능을 가지고 있습니다.. (Java 7 버전 이후 사용 가능)
- 단일 자원 사용 예시
try (Resource resource = getResource()) {
service(resource);
} catch(...) {
...
}
// 1. try문이 끝나면 Resource를 반환하기 때문에 finally 문을 사용해 Resource를 반환할 필요 없다.
// 2. 만약 예외가 발생해서 catch문으로 이동하더라도 Resource를 반환한다.
- 복수 자원 사용 예시
try (Resource resource1 = getResource();
Resource resource2 = getResource()
) {
service(resource1);
service(resource2);
} catch(...) {
...
}
// 1. try문이 끝나면 Resource를 반환하기 때문에 finally 문을 사용해 Resource를 반환할 필요 없다.
// 2. 만약 예외가 발생해서 catch문으로 이동하더라도 Resource를 반환한다.
try - catch문을 설명할 때 사용한 예시를 살펴 보면 BufferedReader와 FileReader클래스가 추상클래스 Reader를 상속받았고, Reader는 Closeable 인터페이스를 상속받았으며, Closeable 인터페이스는 AutoCloseable인터페이스를 상속받았기 때문에 try - with - resources를 이용해서 코드를 가독성 있게 리펙토링 할 수 있습니다.
// try - with - resource를 사용해서 작성
try (FileReader fr = new FileReader("input.txt");
BufferedReader objReader = new BufferedReader(fr)) {
while ((strCurrentLine = objReader.readLine()) != null) {
System.out.println(strCurrentLine);
} catch (IOException e) {
//IOException 발생시 처리하는 구문
e.printStackTrace();
}
참고 사이트
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
'공부방 > Java' 카테고리의 다른 글
에러(Error)와 예외(Exception) (1) | 2023.01.17 |
---|