Java中try()catch{}的使用方法


 第一種寫法:

  try(InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt")){

            /*........................................*/

        } catch (Exception e) {
            e.printStackTrace();
   }

  

第二種寫法:

      try  {
            InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt")
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            
        }

   第一種  情況的()中的代碼一般放的是對資源的申請,如果{}中的代碼出項了異常,()中的資源就會被關閉,這在inputstream和outputstream的使用中會很方便

       第二種  如果{}中的代碼塊出現了異常,會被catch捕獲,然后執行catch中的代碼,接着執行finally中的碼,其中catch中的代碼有了異常才會被執行,finally中的代碼無論有沒有異常都會被執行

 

  從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支持新的 try-with-resources 語句,稱為 ARM 塊(Automatic Resource Management) ,自動資源管理。

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

帶有resources的try語句聲明一個或多個resources。resources是在程序結束后必須關閉的對象。try-with-resources語句確保在語句末尾關閉每個resources。任何實現java.lang.AutoCloseable,包括實現了java.io.Closeable的類,都可以作為resources使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM