在这种情况下:
Cursor cursor = dbHandler.fetchEvents();
boolean someBool = true;
do {
someStuff();
variables = things;
otherStuff();
} while (someBool && cursor.moveToNext());
cursor.moveToNext() 可能会引发许多异常,特别是当我使用游标时数据库意外关闭时。
处理 while() 评估中可能引发的异常的最佳方法是什么?目前,整个事情都崩溃了。我宁愿避免这种情况。编译器不喜欢我直接在 while() eval 中添加 try/catch 的做法,而且它非常丑陋。我想我需要创建一个新方法来执行此操作:
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));
大家还有其他建议吗?如果是这样,我很想听听他们的声音。谢谢!
最佳答案
将整个代码块放入 try/catch block 中,当您失去数据库连接时,该 block 应该捕获。
然后您需要重新研究整个 block 以查看哪些内容需要清理,这将为您提供 try/catch 的“catch block ”的内容。一旦您这样做,您可能会注意到实际代码的进一步改进,这可能会使您发布的这个示例以及当您将您关心的内容归零时建议的相关性降低。
关于java - 在 do ... while() 评估中处理 try/catch 异常的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198204/