gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:26:07 27 4
gpt4 key购买 nike

我有以下代码片段。

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com