作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我们使用 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 个选择:
对于 (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/
我是一名优秀的程序员,十分优秀!