2

How do I handle and rethrow the exception in lambda? When I try to surround the call with try/catch block, it just catches it inside the lambda expression. I have ServiceException in method signature, so I want just to rethrow it. Is it possible or am I missing something?

 BiFunction<Account, LocalDate, AccountBalance> getBalance;

 getBalance = (account, date1) -> balanceProvider.getBalance(account, date1); //balanceProvider.getBalance unhandled ServiceException
developer1
  • 527
  • 4
  • 27
  • There is no standard way to doing this, that doesn't mean it's not possible. Here is some potentially helpful information; https://dzone.com/articles/sneakily-throwing-exceptions-in-lambda-expressions – Jason Mar 17 '20 at 13:18
  • could you show where you're invoking the BiFunction? – Leonardo Meinerz Ramos Mar 17 '20 at 13:19

1 Answers1

2

I used to catch a checked exception and rethrow the unchecked one. Something like:

IntStream.range(1,3).forEach(i -> {
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException("InterruptedException was caught");
        }
    });

Or in your case:

getBalance = (account, date1) -> {
    try {
        balanceProvider.getBalance(account, date1)
    } catch (ServiceException e) {
        throw new ServiceRTException("blabla");
    }
};
Eduard Dubilyer
  • 991
  • 2
  • 10
  • 21