问题
I have the following code snippet.
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.
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?
EDIT:
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));
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.
回答1:
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/hiro0107/java8-try-monad/blob/master/src/main/java/com/github/hiro0107/trymonad/Try.java
Or you can write it yourself.
来源:https://stackoverflow.com/questions/38120915/how-do-i-deal-with-checked-exceptions-in-lambda