How to rethrow exception inside lambda expression?

Viewed 258

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
1 Answers

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");
    }
};
Related