1. 程式人生 > 實用技巧 >Java中try()catch{}的使用方法

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

今天擼程式碼的時候發現了一段這樣的程式碼

try(
            Connection conn=DriverManager.getConnection(url,user,pass);
            Statement stmt=conn.createStatement()
 
         ) {
 
            boolean hasResultSet=stmt.execute(sql);
 
           }

和平常見的不一樣,我們平常見的是這樣的

try{
        fis=new FileInputStream("src\\com\\ggp\\first\\FileInputStreamDemo.java");
        
byte[]bbuf=new byte[1024]; int hasRead=0; while((hasRead=fis.read(bbuf))>0){ System.out.println(new String(bbuf,0,hasRead)); } }catch(IOException e){ e.printStackTrace(); }finally{ try { fis.close(); }
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

  如果{}中的程式碼塊出現了異常,會被catch捕獲,然後執行catch中的程式碼,接著執行finally中的碼,其中catch中的程式碼有了異常才會被執行,finally中的程式碼無論有沒有異常都會被執行,

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

private static void customBufferStreamCopy(File source, File target) {
    try (InputStream fis = new FileInputStream(source);
        OutputStream fos = new FileOutputStream(target)){
  
        byte[] buf = new byte[8192];
  
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 

從網上查閱資料得知從 Java 7 build 105 版本開始,Java 7 的編譯器和執行環境支援新的 try-with-resources 語句,稱為 ARM 塊(Automatic Resource Management) ,自動資源管理。

Thetry-with-resources statement is atrystatement that declares one or more resources. Aresourceis an object that must be closed after the program is finished with it. Thetry-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implementsjava.lang.AutoCloseable, which includes all objects which implementjava.io.Closeable, can be used as a resource.

帶有resources的try語句宣告一個或多個resources。resources是在程式結束後預設掉resources.close(),關閉的資源物件。try-with-resources語句確保在語句末尾關閉每個resources。任何實現java.lang.AutoCloseable,包括實現了java.io.Closeable的類,都可以作為resources使用