當前位置: 妍妍網 > 碼農

為什麽說 與try-finally相比,首選try-with-resources

2024-08-25碼農


在日常開發中,在finally進行io流的關閉,已經成了我們的編碼習慣,甚至可以說是編碼規範。但與 try-finally 結構相比,try-with-resources 通常是更好的選擇,原因如下:

1、自動資源管理

try-with-resources 是為處理 AutoCloseable 型別的資源(如檔、資料庫連線、網路套接字等)而設計的。它會在程式碼塊執行完畢後自動關閉資源,無論程式碼是否正常執行還是丟擲異常。這大大簡化了資源管理,減少了出錯的可能性。

2、更簡潔的程式碼

使用 try-with-resources 可以減少樣板程式碼(boilerplate code)。不需要顯式地在 finally 塊中呼叫資源的 close() 方法。相較之下,try-finally 需要手動編寫關閉資源的程式碼,這不僅繁瑣,還容易遺漏。

3、例外處理更安全

在 try-finally 中,如果 try 塊中的程式碼和 finally 塊中的 close() 方法都丟擲了異常,後者的異常會掩蓋前者。而 try-with-resources 能夠確保 try 塊丟擲的異常不會被忽略,它會將關閉資源時丟擲的異常作為抑制異常(Suppressed Exception)附加到原始異常中,提供更全面的錯誤資訊。

4、防止資源泄漏

try-with-resources 的自動關閉機制可以更有效地防止資源泄漏。對於復雜的程式碼,如果在 try-finally 結構中忘記關閉某些資源或在關閉資源時丟擲異常,可能會導致資源泄漏。而 try-with-resources 能確保資源總是被正確關閉。

5、程式碼範例

下面是一個使用 try-finally 和 try-with-resources 的程式碼範例,透過它們來讀取檔內容,並在完成後關閉檔資源。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public classTryFinallyExample{
publicstaticvoidmain(String[] args){
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
catch (IOException e) {
e.printStackTrace();
finally {
// 確保資源被關閉
if (reader != null) {
try {
reader.close();
catch (IOException e) {
e.printStackTrace(); // 可能掩蓋其他異常
}
}
}
}
}

使用 try-with-resources 的程式碼範例

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public classTryWithResourcesExample{
publicstaticvoidmain(String[] args){
// 使用 try-with-resources 自動管理資源
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
catch (IOException e) {
e.printStackTrace();
}
// 資源會在這裏自動關閉
}
}

6、對比分析

(1)try-with-resources 版本的程式碼更加簡潔,不需要在 finally 塊中顯式地關閉資源。

(2)在 try-finally 版本中,finally 塊中的 close() 方法可能會丟擲異常,並且這個異常可能會掩蓋 try 塊中的異常。而在 try-with-resources 版本中,關閉資源時的異常將作為抑制異常(Suppressed Exception)被附加到原始異常中,不會遺失。

(3)try-with-resources 自動管理資源,確保資源總是在使用完畢後正確關閉,而不依賴開發者手動編寫程式碼進行管理。這有效防止了資源泄漏的風險。

·················END·················

用官方一半價格的錢,用跟官方 ChatGPT4.0 一模一樣功能的工具。

國內直接使用ChatGPT4o:

谷歌瀏覽器直接使用:https://www.nezhasoft.cn

  1. 無需魔法,同時支持手機、電腦

  2. 個人獨享

  3. ChatGPT4o mini永久免費

  4. 支持Copilot、DALLE AI繪畫、上傳檔等

長按辨識下方二維碼,備註ai,發給你

回復gpt,獲取ChatGPT4o直接使用地址

點選閱讀原文,國內直接使用ChatGpt4o