Search code examples
javalambdajava-8java-streamchecked-exceptions

How do I deal with checked exceptions in lambda?


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("[email protected]").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.


Solution

  • You might use some Try<T> container. There are several already written implementations. For example:

    Or you can write it yourself.