0

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!

Yotam Levy
  • 97
  • 2
  • 10

2 Answers2

1

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

Meet Patel
  • 482
  • 4
  • 12
0

One good way to do this is to re-raise the error in your inner catch block. This will hand control to the next-outer try/catch. So, put another try/catch block outside of your foreach construct.

  • The exception occurs and is caught by the innermost try.
  • The printError() stuff is done.
  • The exception is re-raised, which kills the forEach.
  • The try that surrounds the forEach catches the re-raised exception.
Mike Robinson
  • 8,490
  • 5
  • 28
  • 41