Java 9 改進的 try-with-resources

Java 9 新特性 Java 9 新特性

try-with-resources 是 JDK 7 中一個新的異常處理機制,它能夠很容易地關閉在 try-catch 語句塊中使用的資源。所謂的資源(resource)是指在程式完成後,必須關閉的對象。try-with-resources 語句確保了每個資源在語句結束時關閉。所有實現了 java.lang.AutoCloseable 介面(其中,它包括實現了 java.io.Closeable 的所有對象),可以使用作為資源。

try-with-resources 聲明在 JDK 9 已得到改進。如果你已經有一個資源是 final 或等效於 final 變數,您可以在 try-with-resources 語句中使用該變數,而無需在 try-with-resources 語句中聲明一個新變數。

實例

import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } }

輸出結果為:

test

以上實例中我們需要在 try 語句塊中聲明資源 br1,然後才能使用它。

在 Java 9 中,我們不需要聲明資源 br1 就可以使用它,並得到相同的結果。

實例

import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } }

執行輸出結果為:

test

在處理必須關閉的資源時,使用try-with-resources語句替代try-finally語句。 生成的代碼更簡潔,更清晰,並且生成的異常更有用。 try-with-resources語句在編寫必須關閉資源的代碼時會更容易,也不會出錯,而使用try-finally語句實際上是不可能的。

Java 9 新特性 Java 9 新特性