【发布时间】:2015-05-12 17:57:17
【问题描述】:
在这种情况下:
Cursor cursor = dbHandler.fetchEvents();
boolean someBool = true;
do {
someStuff();
variables = things;
otherStuff();
} while (someBool && cursor.moveToNext());
cursor.moveToNext() 可能会引发一些异常,尤其是当我使用游标时我的数据库意外关闭时。
处理 while() 评估中可能引发的任何异常的最佳方法是什么?目前,整个事情都崩溃了。我宁愿避免这种情况。编译器不喜欢我将 try/catch 直接添加到 while() eval 中的努力,而且它非常丑陋。我想我需要创建一个新方法来做到这一点:
private boolean moveToNext(cursor) {
boolean result = false;
try {
result = cursor.moveToNext();
} catch (Exception e) {
... error handling ...
}
return result;
}
然后将我的 eval 循环更改为:
Cursor cursor = dbHandler.fetchEvents();
boolean someBool = true;
do {
someStuff();
variables = things;
otherStuff();
} while (someBool && moveToNext(cursor));
还有人有其他建议吗?如果是这样,我很想听听他们的意见。谢谢!
【问题讨论】:
-
您提出的解决方案正是我所推荐的。
-
我建议将
return result移到 try 或 finally。如果你使用 try/catch,try/catch/finally 应该是你的顶级范围,业务逻辑在 try 块中,错误处理在 catch 块中,以及无论是否存在你想要发生的任何事情finally 块中的错误。
标签: java exception-handling try-catch do-while