標籤:res log imp catch package https gen sources inpu
索引
- 普通的 try.java
- 帶資源的 try.java
- 當資源為 null 的情況
- 可以參考的文檔與資料
/
test.txt
待讀取的內容
hello.
/
普通的 try.java
讀取 test.txt 內容
package example;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class GeneralTry { public static void main(String[] args) { FileInputStream inputStream = null; try { inputStream = new FileInputStream("d:/labs/test.txt"); System.out.println((char) inputStream.read()); // 輸出讀到第一個字元,至於會不會與txt常值內容對應還與txt本身的字元編碼相關。 } catch (FileNotFoundException e) { // 捕獲異常是強制性的,對應 new FileInputStream... e.printStackTrace(); } catch (IOException e) { // 捕獲異常是強制性的,對應 inputStream.read .. e.printStackTrace(); } finally { // 關閉資源是非強制性的,但是我們應該總是這麼做 try { inputStream.close(); if (inputStream != null) { // inputStream 有可能為空白,為了防止出現null 指標而導致程式gg .. inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("如果在輸出窗看到這句話,說明程式沒有gg"); }}/*output=h如果在輸出窗看到這句話,說明程式沒有gg */
/
帶資源的 try.java
同樣是讀取 test.txt 內容
package example;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class ResourceTry { public static void main(String[] args) { try (FileInputStream inputStream = new FileInputStream("d:/labs/test.txt")) { System.out.println((char) inputStream.read()); // 輸出讀到第一個字元,至於會不會與txt常值內容對應還與txt本身的字元編碼相關。 } catch (FileNotFoundException e) { // 捕獲異常仍然是強制的 e.printStackTrace(); } catch (IOException e) { // 捕獲異常仍然是強制的 e.printStackTrace(); } // try 塊退出時,會自動調用 inputStream.close() System.out.println("如果在輸出窗看到這句話,說明程式沒有gg"); }}/*output=h如果在輸出窗看到這句話,說明程式沒有gg*/
/
上述程式(帶資源的 try程式)是在正常情況下(test.txt 檔案存在)啟動並執行,那麼倘若 test.txt 不存在呢?嘗試把 test.txt 改成一個不存在的 test2.txt 輸出結果如下:
/*output=如果在輸出窗看到這句話,說明程式沒有ggjava.io.FileNotFoundException: d:\labs\test2.txt (系統找不到指定的檔案。) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at example.ResourceTry.main(ResourceTry.java:10)*/
如果第一個程式(普通 try)沒有在 inputStream.close() 之前進行非空檢查,程式將會因為 java.lang.NullPointerException 而中止(也就是gg)。
就像上面看到的,帶資源的 try 測試程式同樣可以正常向下執行,所以,帶資源的 try 在調用 close() 前是有進行非空判斷的,這樣就確保了程式正常執行而不拋出 NullPointerException,需要注意的是,除了null 指標異常不會發生, close() 拋出的其它異常需要另當別論!
/
可以參考的文檔與資料:
Try-With Resource when AutoCloseable is null
Possible null pointer exception on autocloseable idiom
The try-with-resources Statement - java tutorials - oracle
Java language specification - 14.20.3
oracle blog - Project Coin:try-with-resources on a null resource
Java 筆記 #02# 帶資源的 try 語句