在这种情况下:在do ... while()评估中处理try/catch异常的最佳方法?
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));
没有人有任何其他建议?如果是这样,我很乐意听到他们。谢谢!
您提出的解决方案正是我所推荐的解决方案。 – tnw
我建议将'return result'移入try或finally。如果你使用try/catch,try/catch/finally应该是你的顶级范围,try块中的业务逻辑,catch块中的错误处理以及任何你想发生的事情,而不管是否存在finally块中的错误。 – Bardicer