我有以下代码片段。
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
的标准内容或类似的东西。
最佳答案
您可能会使用一些Try<T>
容器。
有几个已经编写的实现。例如:
- https://github.com/javaslang/javaslang/blob/master/javaslang/src/main/java/javaslang/control/Try.java
- https://github.com/hiro0107/java8-try-monad/blob/master/src/main/java/com/github/hiro0107/trymonad/Try.java
或者你可以自己写。
关于java - 如何处理 lambda 中的已检查异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38120915/