- 最終更新
- 2026/08/17
3秒でわかる
ファイルや接続の閉じ忘れを防ぐ Java の構文。丸括弧の中で開いた資源を、処理の成否にかかわらず自動的に close してくれます。
30秒図解
もう少し詳しく
どういうものか
try-with-resources は、try のclose() がAutoCloseable を実装した型で、
丸括弧の
なぜ必要か
以前は
try-with-resources では、
具体例
import java.io.*;
import java.sql.*;
public class Main {
void readFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} // ここで br.close() が必ず呼ばれる
}
void query(Connection conn) throws SQLException {
String sql = "SELECT name FROM members WHERE points > ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 100);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
}
}つまずきやすいところ
丸括弧の中で new を
もう 1 つは、System.out を
似た用語との違い
finally は
覚え方
「括弧の

