原始的寫法
先來看一段老代碼
OutputStream out = null; try { out = response.getOutputStream() } catch (IOException e1) { e.printStackTrace(); }finally{ try { if(out != null){ out.close(); } } catch (IOException e2) { e.printStackTrace(); } }
這個輸出流使用了try/catch/finally,寫法繁瑣,並且在關閉的時候也有可能會拋出異常,異常e2 會覆蓋掉異常e1 。
優化后的寫法
Java7提供了一種try-with-resource機制,新增自動釋放資源接口AutoCloseable
在JDK7中只要實現了AutoCloseable或Closeable接口的類或接口,都可以使用try-with-resource來實現異常處理和資源關閉異常拋出順序。異常的拋出順序與之前的不一樣,是先聲明的資源后關閉。
上例中OutputStream實現了Closeable接口,可以修改成:
try(OutputStream out = response.getOutputStream()) { // } catch (IOException e) { e.printStackTrace(); } //如果有多個OutputStream,可以加分號 try(OutputStream out1 = response.getOutputStream(); OutputStream out2 = response.getOutputStream()) { // } catch (IOException e) { e.printStackTrace(); }
這樣寫還有一個好處。能獲取到正確的異常,而非資源關閉時拋出的異常。
還有一點要說明的是,catch多種異常也可以合並成一個了
catch (IOException | SQLException e) { e.printStackTrace(); }
try-with-resource的優點
1、代碼變得簡潔可讀
2、所有的資源都托管給try-with-resource語句,能夠保證所有的資源被正確關閉,再也不用擔心資源關閉的問題。
3、能獲取到正確的異常,而非資源關閉時拋出的異常
附
Closeable 接口繼承了AutoCloseable 接口,都只有一個close()方法,自己新建的類也可以實現這個接口,然后使用try-with-resource機制
public interface AutoCloseable { void close() throws Exception; } public interface Closeable extends AutoCloseable { public void close() throws IOException; }
