【发布时间】:2016-11-02 10:04:34
【问题描述】:
我有以下代码sn-p。
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 或类似的标准内容。
【问题讨论】:
-
不,所有结果都是关于编写大量附加代码来捕获并重新抛出已检查的异常作为运行时异常。
-
所以您认为,这些开发人员都是为了好玩而这样做,而忽略了无需额外代码即可工作的假设解决方案?
标签: java lambda java-8 java-stream checked-exceptions