首页 > 解决方案 > 抛出异常但不停止程序的最佳方法是什么?

问题描述

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

环形

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

我的方法()

// 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的不是好方法。

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

标签: javaexception

解决方案


尝试使用 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

推荐阅读