How do I deal with checked exceptions in lambda? [duplicate]

允我心安 提交于 2021-02-16 15:36:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!