1

I have a following method.

private InternetAddress[] constructToRecipients(final List<String> to) {
    if (to.isEmpty()) {
        throw new IllegalArgumentException("To list can not be empty");
    }
    return to.stream().map(r -> parseEmailAddress(r)).collect(Collectors.toList()).toArray(new InternetAddress[0]);
}

private InternetAddress parseEmailAddress(final String address) {
        try {
            return InternetAddress.parse(address)[0];
        }
        catch (final AddressException e) {
            throw new IllegalArgumentException("Invalid email", e);
        }
    }

I would like to make the parseEmailAddress method throws AddressException like,

private InternetAddress parseEmailAddress(final String address) throws AddressException {
                return InternetAddress.parse(address)[0];
        }

But, not sure how to handling this expception in the caller from lambda.

And, the below call should handle the exception gracefully and throw exception further if the final list is empty.

return to.stream().map(r -> parseEmailAddress(r)).collect(Collectors.toList()).toArray(new InternetAddress[0]);
user1578872
  • 7,808
  • 29
  • 108
  • 206
  • A lambda cannot throw an exception, you **have to** handle it. Here is a good way to do so https://stackoverflow.com/a/18198349/4265049 – Jordan Repovy Feb 13 '18 at 18:20
  • Is there any other simple way like, return toList.stream().map(r -> { try {parseEmailAddress(r);} catch(Exception e){} }).collect(Collectors.toList()).toArray(new InternetAddress[0]); – user1578872 Feb 13 '18 at 18:34
  • 1
    As a side note, you don’t need to do `.collect(Collectors.toList()).toArray(new InternetAddress[0])` when you can simply call `.toArray(InternetAddress[]::new)` on the stream in the first place. – Holger Feb 14 '18 at 10:30

0 Answers0