So I'm looping over a list of accounts and I wanna break the whole "for loop" for all the accounts in the list, and also at the same time to throw an exception as a certain condition is happening:
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);
}
}
Does somebody have any elegant way to do that? Maybe wrapping it with an exception of my own and on this certain case to catch only it? Is there a good and known practice for my demand? I appreciate any help, and tnx a lot!
First thing is - in forEach
you don't have break
functionality like traditional for loop
. so if you need to break for loop use traditional for loop
In Java lambda expression can only throw run-time exception
so one thing you can do this is create CustomeRuntimeException
and wrap forEach loop in try catch
block
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();
}
by dooing this if isSomethingHappens
return ture than CustomeRuntimeException
will throw and it will catched by catch
block and doA()
& doB()
method will execute after catch