引发异常但不停止程序的最佳方法是什么?

时间:2020-01-27 15:11:47

标签: java exception

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

循环

// 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并不是一个好方法。

我希望很清楚,如果不是这样,请随时向我询问更多信息。

2 个答案:

答案 0 :(得分:0)

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

在您的示例中,修改 myMethod()方法以返回布尔值 true (如果成功),并返回 false (否则):< / p>

循环:

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

MyMethod():

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

答案 1 :(得分:0)

尝试使用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
相关问题