gpt4 book ai didi

java - 捕获在 lambda 中抛出的 RuntimeException 并在检查时重新抛出它

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:18 25 4
gpt4 key购买 nike

我想弄清楚为什么我的代码抛出 IllegalStateException,而不是我希望它抛出的自定义异常。

public final class CollectorUtils {
private CollectorUtils() {
throw new UnsupportedOperationException();
}

public static <E, R, X extends Throwable> Collector<E, ?, R> listAndThenCollector(final Predicate<List<E>> listPredicate, final Function<List<E>, R> listFunction, final Function<Throwable, X> exceptionWrapper) throws X {
Objects.requireNonNull(listPredicate);
Objects.requireNonNull(listFunction);
Objects.requireNonNull(exceptionWrapper);
try {
return Collectors.collectingAndThen(Collectors.toList(), list -> {
if (!listPredicate.test(list)) {
throw new IllegalStateException(); //Line that throws the exception
}
return listFunction.apply(list);
});
} catch (IllegalStateException ex) {
throw exceptionWrapper.apply(ex);
}
}

public static <E> Collector<E, ?, E> singleElementCollector() throws NotASingleElementException {
return listAndThenCollector(list -> list.size() == 1, list -> list.get(0), NotASingleElementException::new);
}
}

IllegalStateException 在以下行抛出:throw new IllegalStateException()

示例用法:

public static void test() {
try {
Integer result = IntStream.range(0, 2)
.boxed()
.collect(CollectorUtils.singleElementCollector());
} catch (NotASingleElementException ex) {
Logger.getLogger(CollectorUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}

这段代码应该抛出一个 NotASingleElementException,而不是抛出一个 IllegalStateException,我怎样才能让它工作?

实际工作中的错误行为跟踪:

Exception in thread "pool-3-thread-1" java.lang.IllegalStateException
at dpc2.base.utils.CollectorUtils.lambda$listAndThenCollector$0(CollectorUtils.java:28)
at dpc2.base.utils.CollectorUtils$$Lambda$21/2071035411.apply(Unknown Source)
at java.util.function.Function.lambda$andThen$6(Function.java:88)
at java.util.function.Function$$Lambda$22/63121782.apply(Unknown Source)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:503)
at dpc2.base.utils.ImageMagickUtils.convertPDFToTIFF(ImageMagickUtils.java:30)
at dpc2.server.convert.ConvertConsumer.accept(ConvertConsumer.java:20)
at dpc2.server.convert.ConvertConsumer.accept(ConvertConsumer.java:14)
at dpc2.base.checker.BaseChecker.lambda$null$0(BaseChecker.java:116)
at dpc2.base.checker.BaseChecker$$Lambda$15/2121862243.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)

最佳答案

您的收集器在 listAndThenCollector 方法中返回但未收集。实际收集发生在:

.collect(CollectorUtils.singleElementCollector());

在你的测试方法中。那就是抛出异常的时候。

关于java - 捕获在 lambda 中抛出的 RuntimeException 并在检查时重新抛出它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22958624/

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