gpt4 book ai didi

java - 未处理的异常在两种不同的方法上的工作方式不同

转载 作者:行者123 更新时间:2023-11-29 04:08:43 25 4
gpt4 key购买 nike

我在第二种方法 getByIds 上得到了 Unhandled exception works differently on two different methods这是没有意义的。我在第二个方法中调用了第一个方法,并已将 try catch 放入。

对这个异常(exception)有什么想法吗?谢谢

@Override
public PostPayload getById(@NotNull UUID issueId) throws APIException {
try (...) {
return test.apply(responseIssue, issueAuxiliaryData);
} catch (IOException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);
}
}

@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new APIException("Unable to retrieve XXX for issueId=" + issueId, e);

}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

最佳答案

你可以做两件事,但有一个异常(exception):

  1. 以某种方式处理它
  2. 重新抛出

您的第一个方法在其签名中有一个 throws APIException,因此抛出 APIException 是一件有效的事情。

但这与您的其他方法有何不同?您试图从传递给 stream().map() 方法的 lambda 中抛出异常。从文档中我们可以找到这个lambda对应的功能接口(interface):

public interface Function<T, R> {
R apply(T t);
}

从签名中我们可以看出它没有抛出任何已检查的异常,因此从 lambda 中抛出 APIException 是编译错误(假设 APIException 是已检查的异常(exception))

一个可能的解决方法是定义另一个版本的异常,它派生自 RuntimeException,例如 UncheckedApiException。然后你可以将整个流操作包装在一个大的 try-catch block 中,然后在 catch block 中你可以抛出检查过的版本:

@Override
public List<PostPayload> getByIds(@NotNull Set<UUID> issueIds) throws APIException {
try {
return issueIds.parallelStream()
.map(issueId -> {
try {
return this.getById(issueId, channelId, false);
} catch (IOException | APIException e) {
logger.error("Event='Unable to retrieve XXX ', issueId={}", issueId, e);
throw new UncheckedApiException("Unable to retrieve XXX for issueId=" + issueId, e);

}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} catch (UncheckedApiException e) {
throw new APIException(e);
}
}

关于java - 未处理的异常在两种不同的方法上的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517620/

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