简体   繁体   English

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

[英]What is the best way to throw an Exception but not stop the program?

Please find below an example of my need.请在下面找到我需要的示例。 Indeed, I don't want to close the entire process because even if it throw an Exception, it can continue.确实,我不想关闭整个过程,因为即使它抛出异常,它也可以继续。

Loop环形

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

Maybe that used throw new is not the good way to do.也许使用throw new不是好方法。

I hope it is clear, if it is not, do not hesitate to ask me more informations.我希望很清楚,如果不是,请随时向我询问更多信息。

Don't throw an exception.不要抛出异常。 Handle the method failure whichever way you see fit.以您认为合适的方式处理方法失败。

In your example, modify the myMethod() method to return boolean true if it was successful and false if it was not:在您的示例中,修改myMethod()方法以在成功时返回布尔值true ,否则返回false

Loop:环形:

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

Try to use try-catch statement.尝试使用 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

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

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