Java筆記 #02# 帶資源的try語句

索引

  1. 普通的 try.java
  2. 帶資源的 try.java
  3. 當資源爲 null 的狀況
  4. 能夠參考的文檔與資料

 

/html

test.txtjava

待讀取的內容oracle

hello.

/測試

普通的 try.java編碼

讀取 test.txt 內容spa

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 有可能爲空,爲了防止出現空指針而致使程序gg ..
 inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("若是在輸出窗看到這句話,說明程序沒有gg"); } } /* output= h 若是在輸出窗看到這句話,說明程序沒有gg */

 /指針

帶資源的 try.javacode

一樣是讀取 test.txt 內容htm

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 */

 /blog

上述程序(帶資源的 try程序)是在正常狀況下(test.txt 文件存在)運行的,那麼假若 test.txt 不存在呢?嘗試把 test.txt 改爲一個不存在的 test2.txt 運行帶資源的 try 測試程序輸出結果以下:

/* output= 若是在輸出窗看到這句話,說明程序沒有gg java.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,須要注意的是,除了空指針異常不會發生, 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

再補充幾個:

Exception coming out of close() in try-with-resource

Is it important to add AutoCloseable in java?

How should I use try-with-resources with JDBC?

相關文章
相關標籤/搜索