[問題] 關於try-with-resource

作者: plokmijnuhb (..)   2018-06-20 22:47:32
最近用cursor注意到java有try-with-resource可用
看起來類似以前用過C#的using,在statement結束時會自動close resource
程式碼寫起來類似
try(Cursor cursor = getContentResolver().query(xxxx)) {
// do something
} catch (Exception ex) {
// handle exception
}
我的問題是cursor真的會保證close嗎?
程式執行的順序應該會是
cursor.close() -> catch
假如cursor發生exception的話
也能在這個catch中hook到嗎?
萬一沒有的話, 是不是就memory leak了?
以前的寫法好像也差不多,還保證exception都撈的到
Cusor cursor = null;
try {
cursor = getContentResolver().query(xxxx);
} catch(Exception ex) {
// handle exception
} finally {
try {
if(cursor != null && !cursor.isClose()) {
cursor.close();
}
} catch(Exception ex) {
//handle exception
}
}
作者: salavida (席阿)   2018-06-20 23:39:00
Cursor有implements Closeable try-with一定能close
作者: y3k (激流を制するは静水)   2018-06-21 20:01:00
你把Cursor換成JSONObject看他會怎麼錯就知道了
作者: ssccg (23)   2018-06-21 22:02:00
try resource就是自動幫寫finally close啊..就不用把變數scope擴大到try block外面,也不用檢查null還要處理close的exception,那些都多寫的...另外沒close是resource leak,不是memory leak

Links booklink

Contact Us: admin [ a t ] ucptt.com