繁体   English   中英

在do…while()评估中处理try / catch异常的最佳方法?

[英]Best way to handle a try/catch exception in a do … while() evaluation?

在这种情况下:

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;
}

然后将我的评估循环更改为:

Cursor cursor = dbHandler.fetchEvents();
boolean someBool = true;

do {
    someStuff();
    variables = things;
    otherStuff();
} while (someBool && moveToNext(cursor));

还有其他建议吗? 如果是这样,我很想听听他们的声音。 谢谢!

将整个代码块放在try / catch块中,当您失去数据库连接时应捕获该代码块。

然后,您需要重新调查整个块,以查看清理的意义,这将为您提供try / catch的“ catch块”的内容。 完成此操作后,您可能会注意到真实代码的进一步改进,这可能会使您发布的示例变得不那么重要了,并且在您关注所关注的内容时,建议也变得不那么相关了。

这实际上取决于遇到错误时要发生的情况。 当您获得Exception时,您是否应该跳过该循环的迭代并继续进行下一个迭代,或者只是停止迭代? 还是整个循环陷入困境,您需要告诉用户出了什么问题?

如果您真的很想分别处理循环的每个迭代,那么您的方法会很好用。 或者,如果您只想检测整个循环是否遇到错误,则可以将整个内容包装在try块中:

try {
   Cursor cursor = dbHandler.fetchEvents();
   boolean someBool = true;

   do {
        someStuff();
        variables = things;
        otherStuff();
   } while (someBool && cursor.moveToNext());
} catch (Exception e) {
  //report to the user that the loop failed
}

您始终可以将while()的代码移动到循环主体中,没什么大不了的

while(true)
{

    ...
    if( ! someBool )
        break;
    if( ! cursor.moveNext() )
        break;
}

然后用您喜欢的任何代码将其包围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM