I have a for
loop as below which is working fine.
try {
Accountant accountant = getAccountant(employees);
for (Employee person : employees) {
accountant.pay(person, this); // throws BudgetIsOverException
}
allSalariesPaid = true;
}
catch (BudgetIsOverException e){
allSalariesPaid = false;
}
But when I use a stream API instead, it asks me to handle the BudgetIsOverException
and shows an error at accountant.pay
even though it is properly caught after the try
statement. Below the code:
try {
Accountant accountant = getAccountant(employees);
employees.stream()
.forEach(e->accountant.pay(e,this)); // throws BudgetIsOverException
allSalariesPaid = true;
}
catch (BudgetIsOverException e) {
allSalariesPaid = false;
}
My question is why is stream API expecting an exception to be caught inside the foreach
block?