728x90
try-with-resources란?
try-with-resources는 Java 7에서 도입된 기능으로, 자동 리소스 해제(AutoCloseable) 기능을 제공하는 try 문이다.
사용 목적
- 파일, 소켓, 데이터베이스 연결 등의 외부 리소스를 사용하는 경우 반드시 닫아줘야 함.
- 기존에는 finally 블록에서 close()를 호출해야 했지만, try-with-resources를 사용하면 자동으로 리소스를 닫아줌.
사용 방법
리소스를 try 괄호 안에서 선언하면, try 블록이 끝날 때 자동으로 close()가 호출된다.
기본 문법
try (리소스 선언) {
// 리소스를 사용하는 코드
} catch (예외) {
// 예외 처리 코드
}
예제 1: 파일 읽기 (FileInputStream)
import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
설명
- FileInputStream, InputStreamReader, BufferedReader를 try-with-resources 안에서 선언.
- try 블록이 끝나면 자동으로 close() 호출.
예제 2: JDBC 데이터베이스 연결
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TryWithResourcesJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "1234";
String sql = "SELECT * FROM users";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
System.out.println("User: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
설명
- Connection, PreparedStatement, ResultSet을 try-with-resources로 선언.
- 블록이 끝나면 자동으로 연결이 종료됨.
예제 3: 직접 AutoCloseable 구현
try-with-resources는 AutoCloseable 인터페이스를 구현한 클래스에서만 동작함.
class MyResource implements AutoCloseable {
public void doSomething() {
System.out.println("리소스 사용 중...");
}
@Override
public void close() {
System.out.println("리소스가 자동으로 닫힘.");
}
}
public class CustomResourceExample {
public static void main(String[] args) {
try (MyResource resource = new MyResource()) {
resource.doSomething();
}
}
}
실행 결과
리소스 사용 중...
리소스가 자동으로 닫힘.
기존 try-finally 방식과 비교
기존 try-finally 방식
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
❌ 단점
- finally 블록에서 close()를 호출해야 해서 코드가 길어짐.
- close()에서 예외가 발생할 경우 추가적인 예외 처리가 필요함.
try-with-resources의 장점
✅ 코드가 간결함
✅ 자동으로 리소스를 닫아줌 → finally 블록이 필요 없음
✅ close()에서 예외가 발생해도 안전
정리
- try-with-resources는 AutoCloseable 인터페이스를 구현한 리소스를 자동으로 닫아줌.
- try 블록이 끝나면 close()가 자동 호출됨.
- 기존 try-finally 방식보다 코드가 간결하고 안전함.
- Java 7 이상에서 사용 가능.
💡 파일, 네트워크, 데이터베이스 리소스를 사용할 때 적극 활용하면 좋음!
728x90
'개발 > 자바' 카테고리의 다른 글
| 메소드 접근 제어자 public, protected, private, default (0) | 2025.02.18 |
|---|---|
| java : import static (0) | 2025.02.18 |
| ScheduledThreadPool 샘플(매일 오전 1시 실행) (0) | 2025.02.17 |
| Thread ExecutorService API (0) | 2025.02.17 |
| Thread 설정 및 주요 메서드 (0) | 2025.02.17 |