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?

相关文章
相关标签/搜索