gpt4 book ai didi

java - 如何在 Java 中处理仿函数对象内的已检查异常

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

我们使用 http://jedi.codehaus.org用于处理集合并以功能方式操作它们的库。我们最近在执行类似以下操作时遇到了一个问题:

public class Address {
//constructors and stuff

public KiloWatts electricityConsumed(Duration timePeriod) throw NoElectricitySupply {
.... does stuff but can throw checked exception
}
}

假设我们有一个地址集合,并且我们想对与每个地址关联的 UnitsOfElectricity 执行某些操作,您将如何处理抛出的异常,例如:

public KiloWatts totalEnergyConsumed(Address... addresses, final Duration timePeriod) {
List<KiloWatts> energyConsumedPerAddress = FunctionalPrimitives.collect(addresses, new Functor<Address, KiloWatts>{
public KiloWatts execute(Address address){
try {
return address.energyConsumed(timePeriod);
} catch (NoElectricitySupply e) {

//What do you do here?

}
}
});
}

你会如何处理异常?

最佳答案

据我所知,您有 2 个选择:

  1. 抛出运行时异常(并忽略它);或
  2. 抛出运行时异常,使用它来“编码”经过接口(interface)边界的已检查异常。

对于 (2),类似于:

public KiloWatts totalEnergyConsumed(Address... addresses, final Duration timePeriod) {
try {
List<KiloWatts> energyConsumedPerAddress = FunctionalPrimitives.collect(addresses, new Functor<Address, KiloWatts>{
public KiloWatts execute(Address address){
try {
return address.energyConsumed(timePeriod);
} catch (NoElectricitySupply e) {
throw new RuntimeException("internal marshalling exception", e);
}
}
});
} catch(RuntimeException re) {
throw e.getCause();
}
}

关于java - 如何在 Java 中处理仿函数对象内的已检查异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942827/

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