Idiom to close a cursor

后端 未结 7 1696
刺人心
刺人心 2021-02-08 03:57

Which of the following two should I be using to make sure that all the cursors are closed?

    Cursor c = getCursor(); 

    if(c!=null && c.getCount()&g         


        
7条回答
  •  梦谈多话
    2021-02-08 04:38

    Neither, but the second one was closest.

    • Option 1 doesn't properly close the Cursor when getCount() == 0
    • Option 2 leaves the finally block exposed to a null pointer exception

    I would use:

    Cursor c = getCursor(); 
    try { 
        if(c!=null && c.getCount()>0){ 
             // do stuff with the cursor
        }
    }
    catch(..) {
        //Handle ex
    }
    finally { 
        if(c != null) {
            c.close(); 
        }
    }
    

    ... or if you expect the cursor to be null frequently, you could turn it on its head a little bit:

    Cursor c = getCursor(); 
    if(c != null) {
        try { 
            if(c.getCount()>0) { 
                 // do stuff with the cursor
            }
        }
        catch(..) {
            //Handle ex
        }
        finally { 
            c.close(); 
        }
    }
    

提交回复
热议问题