中断 for 循环,并在发生特定条件时引发异常



所以我正在循环一个帐户列表,我想打破列表中所有帐户的整个"for 循环",同时在发生特定条件时抛出异常:

accounts.forEach(account -> {
try {
if (isSomethingHappens()) {
String errorMsg = "bla bla, you can't do that cuz condition is happening";
printError(errorMsg);
throw new Exception(errorMsg); // AND I also, in addition to the exception, I wanna break the whole loop here
}
doA();
doB();
} catch (Exception e) {
printError(e);
}
}

有人有什么优雅的方式来做到这一点吗? 也许用我自己的例外来包装它,并且在某些情况下只抓住它? 对于我的需求,是否有良好且已知的实践? 我感谢任何帮助,并且非常感谢!

第一件事是 - 在forEach中,您没有像传统for loop那样break功能。 因此,如果您需要中断循环,请使用传统for loop在 Java 中,lambda 表达式只能抛出运行时异常因此,您可以做的一件事是创建CustomeRuntimeException并在try catch块中包装每个循环

try {
accounts.forEach(account -> {
if (isSomethingHappens()) {
throw new CustomeRuntimeException("bla bla, you can't do that cuz condition is happening");
}
}
} catch (CustomeRuntimeException e) {
printError(e);
}
doA();
doB();
}

通过做这个,如果isSomethingHappens返回 ture 比CustomeRuntimeException会抛出,它会被catch块捕获,doA()&doB()方法将在捕获后执行

一个好方法是在内部catch块中重新引发错误。 这会将控制权交给下一个外部尝试/捕获。 因此,在foreach构造之外放置另一个 try/catch 块。

  • 发生异常并被最里面的try捕获。
  • printError()的事情已经完成。
  • 重新引发异常,这会杀死forEach
  • 围绕forEachtry捕获重新引发的异常。

最新更新