gpt4 book ai didi

java - 使用自定义消息完成for循环后引发异常

转载 作者:行者123 更新时间:2023-12-03 08:19:12 26 4
gpt4 key购买 nike

我该如何使用Exception传递失败方法的变量?我有一个for循环,每次循环迭代失败时,它将变量添加到失败项列表中,然后将其传递给异常并使用getMessage()打印。

public class SendMail {
public void send(List<String> inputlist) throws MessagingException {
List<String> failedItems = new ArrayList<>();
for (String item : inputlist) {
try {
// Do something
} catch (Exception e) {
failedRecipients.add(item);
continue;
}
}
// Custom exception with string of failed items.
if (!failedItems.isEmpty()) {
throw new MessagingException(String.join(",", failedItems));
}
}
}
public class ProcessStep {
public void execute(List<String> inputlist) throws XferException {
try {
sendmail.send(inputlist); //String list gets passed here.
} catch (MessagingException e) {
log.logger("Failed for items: " + e.getMessage()) //Print string of failed items here
}
throw new MalwareException;
}
}
}

有没有更优雅的方式做到这一点?

最佳答案

您可以使用带有任意数量参数的构造函数来定义自定义异常。

关于java - 使用自定义消息完成for循环后引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61665734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com