差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

java:effective_java:creating_and_destroying_objects:prefer_try-with-resources_to_try-finally [2019/07/28 22:30]
tony [Introduction & My Opinion]
java:effective_java:creating_and_destroying_objects:prefer_try-with-resources_to_try-finally [2023/06/25 09:48]
行 1: 行 1:
-{{tag>​java effective_java}} +
-====== Effective Java - Prefer try-with-resources to try-finally ====== +
-===== Introduction & My Opinion ===== +
-在Java7以前,針對需要特別close的資源,會寫程式的人基本上都會放在finally的block中:​ +
-<code java> +
-    private void close(Closeable closable){ +
-        try { +
-            if( closable != null ) +
-                closable.close();​ +
-        } catch (IOException e) { +
-            // log +
-        } +
-    } +
-  +
-    private void load(){ +
-        mProp = new Properties();​ +
-        InputStream is = null; +
-        try { +
-            is = new FileInputStream(mConfigFilePath);​ +
-            mProp.load(is ); +
-        } catch (IOException e) { +
-            // need to handle .. +
-        } finally { +
-            close(is);​ +
-        } +
-    } +
-</​code>​ +
-這個item要強調的是,在Java7之後,使用try-with-resources會讓你的程式碼更精簡:​ +
-<code java> +
-        try( InputStream is = new FileInputStream(mConfigFilePath) ){ +
-    mProp.load(is);​ +
-    } catch (IOException e) { +
-            // need to handle .. +
-        } +
-</​code>​ +
-針對使用的說明,我之前已有[[java:​basic:​exception:​try-with-resource|文章]]做分享。這種寫法除了讓你程式碼更精簡外,以上述例子來說,如果load與close都發生例外,是可以透過getSuppressed去取得這兩個的callstack。\\ +
-\\ +
-這種寫法也可以應用在stream的close,甚至可以做自己的AutoClose的Lock物件,避免忘記呼叫unlock的情況。 +
-===== Note ===== +
-Effective Java第三版Item 9。 +
-===== Reference ===== +
-  * Effective Java, 3/e +
-=====    ===== +
----- +
-\\ +
-~~DISQUS~~+