如何处理lambda中的检查异常? [英] How do I deal with checked exceptions in lambda?
问题描述
我有以下代码段.
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);
}
}
}
}
}
由于以下错误,它无法编译.
This does not compile because of the following error.
未处理的异常类型AddressException
Unhandled exception type AddressException
我进行了一些研究,所有解决方案都只是将检查到的异常包装在自定义方法中的运行时异常中.我想避免为这些东西编写其他代码.有什么标准方法可以处理此类情况?
I have researched a little and all the solutions were only with wrapping the checked exception in a runtime exception in a custom method. I want to avoid writing additional code for that stuff. Is there any standard way to handle such cases?
到目前为止,我所做的是
What I have done so far is
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
或类似的标准内容.
but it does not look nice. I could swear that in one of the tutorials I have seen something standard with rethrow
or something similar.
推荐答案
您可能会使用某些Try<T>
容器.
有几种已经编写的实现.例如:
You might use some Try<T>
container.
There are several already written implementations. For example:
- https://github.com/javaslang/javaslang/blob/master/javaslang/src/main/java/javaslang/control/Try.java
- 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
或者您可以自己编写.
这篇关于如何处理lambda中的检查异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!