這是本文件的舊版!


Effective Java - Prefer try-with-resources to try-finally

在Java7以前,針對需要特別close的資源,會寫程式的人基本上都會放在finally的block中:

    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);
        }
    }
這個item要強調的是,使用try-with-resources會讓你的程式碼更精簡:
        try( InputStream is = new FileInputStream(mConfigFilePath) ){
    		mProp.load(is);
    	} catch (IOException e) {
            // need to handle ..
        }

Effective Java第三版Item 9。

  • Effective Java, 3/e