Java8 Lambda - 处理异常

时间:2018-02-13 18:02:37

标签: java lambda java-8

我有以下方法。

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

我想让parseEmailAddress方法抛出AddressException,如

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

但是,不确定如何在lambda的调用者中处理这个expception。

并且,如果最终列表为空,则下面的调用应该优雅地处理异常并进一步抛出异常。

return to.stream().map(r -> parseEmailAddress(r)).collect(Collectors.toList()).toArray(new InternetAddress[0]);

0 个答案:

没有答案