看板 AndroidDev 關於我們 聯絡資訊
最近用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 } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.34.126.161 ※ 文章網址: https://www.ptt.cc/bbs/AndroidDev/M.1529506055.A.F1A.html
salavida: Cursor有implements Closeable try-with一定能close 06/20 23:39
y3k: 你把Cursor換成JSONObject看他會怎麼錯就知道了 06/21 20:01
ssccg: try resource就是自動幫寫finally close啊.. 06/21 22:02
ssccg: 就不用把變數scope擴大到try block外面,也不用檢查null還 06/21 22:05
ssccg: 要處理close的exception,那些都多寫的... 06/21 22:05
ssccg: 另外沒close是resource leak,不是memory leak 06/21 22:06