【问题标题】:What is the best way to throw an Exception but not stop the program?抛出异常但不停止程序的最佳方法是什么?
【发布时间】:2020-01-27 15:11:47
【问题描述】:

请在下面找到我需要的示例。确实,我不想关闭整个进程,因为即使抛出异常,它也可以继续。

循环

// set a lot of variables and execute some methods
for (int i = 0, i < items.length; i++) {
     // blablabla
     myMethod()
     // blablabla2
}
// some code here also

MyMethod()

// blabla
if (!found)
     throw new EndCurrentProcessException()
// blabla

EndCurrentProcessException

public void EndCurrentProcessException() {
     ??? What I'm supposed to put here to stop the loop iteration ???
}

也许使用throw new 不是好方法。

我希望很清楚,如果没有,请随时向我询问更多信息。

【问题讨论】:

  • Indeed, I don't want to close the entire process - What I'm supposed to put here to stop the CURRENT process 所以你要不要阻止它?不清楚你在问什么
  • 你的意思是停止执行MyMethod()?当然,在记录任何错误或通知用户失败等之后,您总是可以只 return;
  • 您的异常应该描述错误行为是什么,而不是处理问题本身。所谓流程,是指循环中的迭代吗?
  • 一开始为什么要抛出异常?例外用于您没有影响的事物(文件 IO、网络、硬件等)。
  • Try-catch 块

标签: java exception


【解决方案1】:

不要抛出异常。以您认为合适的方式处理方法失败。

在您的示例中,修改 myMethod() 方法,如果成功则返回布尔值 true,否则返回 false

循环:

// set a lot of variables and execute some methods
for (int i = 0, i < items.length; i++) {
   // blablabla
   if (!myMethod()) {
       // Skip this particular ITEM...
       continue;
       // Or whatever you want.
   }
   // blablabla2
}

我的方法():

public boolean myMethod() {
    // ... Method code ...
    if (!found) {
        return false;
    }
    // ... Possibly more Method code ...
    return true;
}

【讨论】:

    【解决方案2】:

    尝试使用 try-catch 语句。

    for (int i = 0, i < items.length; i++) {
        // blablabla
        try {
            myMethod();
        } catch(EndCurrentProcessException e){
            // do something or continue;
            continue;
        }
        // blablabla2
     }
     // some code here also
    

    【讨论】:

    • 捕获异常会停止正在进行的执行吗?
    猜你喜欢
    • 2018-08-11
    • 2014-05-23
    • 2010-09-22
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2010-12-09
    相关资源
    最近更新 更多