如何处理lambda中的已检查异常?

时间:2016-06-30 10:48:43

标签: java lambda java-8 java-stream checked-exceptions

我有以下代码段。

package web_xtra_klasa.utils;

import java.util.Arrays;
import java.util.Properties;
import java.util.function.Function;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
    public static void main(String[] args) throws Exception {
        Transport transport = null;
        try {
            final Properties properties = new Properties();
            final Session session = Session.getDefaultInstance(properties, null);
            final MimeMessage message = new MimeMessage(session);
            final String[] bcc = Arrays.asList("user@example.com").stream().toArray(String[]::new);
            message.setRecipients(Message.RecipientType.BCC, Arrays.stream(bcc).map(InternetAddress::new).toArray(InternetAddress[]::new));
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (final MessagingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

由于以下错误,无法编译。

  

未处理的异常类型AddressException

我已经研究了一点,并且所有解决方案都只是将自定义方法中的已检查异常包装在运行时异常中。我想避免为那些东西编写额外的代码。有没有标准的方法来处理这种情况?

编辑:

到目前为止,我所做的是

message.setRecipients(Message.RecipientType.BCC,
        Arrays.stream(bcc).map(e -> {
            try {
                return new InternetAddress(e);
            } catch (final AddressException exc) {
                throw new RuntimeException(e);
            }
        }).toArray(InternetAddress[]::new));

但看起来并不好看。我可以发誓,在其中一个教程中,我看到了rethrow或类似内容的标准。

1 个答案:

答案 0 :(得分:3)

相关问题