try-with-resources trong Java là gì? Ưu điểm so với finally?
try-with-resources trong Java là gì? Ưu điểm so với finally?
try-with-resources (Java 7) tự động đóng tài nguyên khi khối try kết thúc, kể cả khi có exception. Tài nguyên phải implement AutoCloseable (hoặc Closeable).
// Cách cũ: dài, dễ quên, dễ che mất exception
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(path));
return reader.readLine();
} finally {
if (reader != null) reader.close(); // close() cũng có thể ném exception
}
// Cách mới
try (var reader = Files.newBufferedReader(Path.of(path))) {
return reader.readLine();
}
Connection, PreparedStatement, ResultSet, stream, ExecutorService (Java 19+).Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.