try-with-resources 是 Java 7 引入的一种异常处理机制,用于自动管理资源(如文件流、数据库连接等),确保资源在使用后能够被正确关闭,无需显式调用 close() 方法。
基本语法
java
try (ResourceType resource1 = new ResourceType();
ResourceType resource2 = new ResourceType()) {
// 使用资源的代码
} catch (Exception e) {
// 异常处理
}
用法示例
java
import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "username";
String password = "password";
// 自动关闭Connection和Statement
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
while (rs.next()) {
System.out.println("用户ID: " + rs.getInt("id") +
", 用户名: " + rs.getString("username"));
}
} catch (SQLException e) {
System.err.println("数据库错误: " + e.getMessage());
}
}
}