成语关闭游标游标、成语

由网友(兄弟在中国)分享简介:以下哪两个,我应该使用,以确保所有的游标都关闭?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.getCo...

以下哪两个,我应该使用,以确保所有的游标都关闭?

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()>0){ 
        try{ 
            // read values from cursor 
        }catch(..){} 
        finally{ 
            c.close(); 
        } 
    }//end if

    OR

    Cursor c = getCursor(); 
    try{ 
        if(c!=null && c.getCount()>0){ 
            // read values from cursor 
        }//end if 
    }catch(..){

    }finally{ 
        c.close(); 
    } 

编辑: 几个问题: 1.我们需要调用close()上的光标,其具有0计数? 2.因为在这种情况下,第成语,close()方法将永远不会被调用。它假设为无元素的光标,光标将永远不会被打开。这是一个有效的假设?

A few questions: 1. Do we need to call close() on a cursor which has count of 0? 2. Because in that case for the first idiom, close() will never be called. It assumes that for a cursor having no elements, cursor will never be opened. Is this a valid assumption?

请指教。

推荐答案

都不是,但第二个是最接近的。

Neither, but the second one was closest.

选项1不正确关闭 游标时getCount将()== 0 选项2叶finally块暴露在空指针异常 Option 1 doesn't properly close the Cursor when getCount() == 0 Option 2 leaves the finally block exposed to a null pointer exception

我会用:

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

...或者,如果你希望光标为null频繁,你可以把它在它的头一点点:

... 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(); 
    }
}
阅读全文

相关推荐

最新文章