关闭光标的习惯用法
我应该使用以下哪两个来确保所有游标都关闭?
Cursor c = getCursor();
if(c!=null && c.getCount()>0){
try{
// read values from cursor
}catch(..){}
finally{
c.close();
}
}//end if
或
Cursor c = getCursor();
try{
if(c!=null && c.getCount()>0){
// read values from cursor
}//end if
}catch(..){
}finally{
c.close();
}
请指教。
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();
}
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
两者都不是,但第二个最接近。
Cursor when getCount() == 0
我会使用:
...或者如果您希望游标经常为空,您可以稍微扭转一下它:
Neither, but the second one was closest.
Cursor when getCount() == 0
I would use:
... or if you expect the cursor to be null frequently, you could turn it on its head a little bit:
这甚至更好:
代码:
请注意,如果出现错误或空游标,
c
可能为 null。请参阅https://stackoverflow.com/a/16108435/952135。不过,如果游标为空,我会报告空返回值作为错误。This is even better:
The code:
Note that
c
might be null in case of error or empty cursor. See https://stackoverflow.com/a/16108435/952135. I would report null return value in case of empty cursor as a bug, though.最佳实践如下:
Best practice is the one below:
取决于您要捕获的内容,但我会说第二个,以防万一
c.getCount()
抛出异常。另外,一些缩进不会出错:)
Depends on what you're catching, but I'd say the second one, just in case
c.getCount()
throws an exception.Also, some indentation wouldn't go amiss :)
我会说第一个,主要是因为第二个即使
c
为null
也会尝试调用c.close()
。另外,根据文档,getCount()
不会引发任何异常,因此无需将其包含在
try
块中。I'd say the first one, mainly because the second one will try to call
c.close()
even ifc
isnull
. Also, according to the docs,getCount()
doesn't throw any exceptions, so there's no need to include it in thetry
block.我认为我的答案是最好的:
I think my answer is the best one :
我认为@skylarsutton 是这个问题的正确答案。但是,我想留下问题的代码(答案中的任何代码似乎都有一些缺陷)。请考虑使用我的代码。
I think @skylarsutton's is a right answer for the question. However, I want to leave codes for the question (any codes in answers seems to have some flaws). Please consider to use my code.