[問題] 關於try-with-resource

看板AndroidDev作者 (..)時間6年前 (2018/06/20 22:47), 編輯推噓1(105)
留言6則, 3人參與, 6年前最新討論串1/1
最近用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

06/20 23:39, 6年前 , 1F
Cursor有implements Closeable try-with一定能close
06/20 23:39, 1F

06/21 20:01, 6年前 , 2F
你把Cursor換成JSONObject看他會怎麼錯就知道了
06/21 20:01, 2F

06/21 22:02, 6年前 , 3F
try resource就是自動幫寫finally close啊..
06/21 22:02, 3F

06/21 22:05, 6年前 , 4F
就不用把變數scope擴大到try block外面,也不用檢查null還
06/21 22:05, 4F

06/21 22:05, 6年前 , 5F
要處理close的exception,那些都多寫的...
06/21 22:05, 5F

06/21 22:06, 6年前 , 6F
另外沒close是resource leak,不是memory leak
06/21 22:06, 6F
文章代碼(AID): #1RAca7yQ (AndroidDev)