最近用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
}
}