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

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

由于出现以下错误,因此无法编译。

Unhandled exception type 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 的标准内容或类似的东西。

最佳答案

关于java - 如何处理 lambda 中的已检查异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38120915/

相关文章:

java - 默认为空白的 JSP 下拉列表

java jvisualvm/jconsole 具有线性内存消耗

java - String hashCode() 文档与实现

java - Roadblock 在 Windows 上为 Android 设置我的 Phonegap 环境

java - 尝试使用 cygwin 执行 jar,无法识别参数

java - 如何仅接受 JTextField 中的指定模式?

c# - 优化通用列表 WHERE

python - 使用Python的过滤功能

lambda - 从Kendo UI网格中创建具有相关对象的表达式[FilterDescriptor]

java - Windows Defender 阻止在 Java 中获取指针位置