有没有处理任何方式 - 并继续 - 在保持foreach语法糖的同时迭代器中的异常?
没有这样的糖。
偶尔行将语法上伪造,但这并不意味着我们不应该继续阅读文件。
那么,如果它不是特殊的行是假的,为什么会抛出异常?你可以重写你的迭代器。假设您目前迭代ParsedThingy
实例和解析器抛出ThingyParseException
如果解析失败,遍历包装这让您查询bogusness的解析结果,就像这样:
for (Possibly<ParsedThingy, ThingyParseException> p : parser) {
if (p.exception() != null) handleException(p.exception());
else doSomethingExcitingWith(p.value());
}
某种程度上更自我记录比看似自发地返回null
s;它还可以让您向客户端代码提供有关错误的信息。
Possibly<V, X>
是一个可能实际上是一个例外的值的包装。您可以通过检查exception()
非空查询一个特殊的地位,并通过调用value()
得到的非特殊情况下的值(这将抛出,如果它是一个例外):
class Possibly<V, X extends Throwable> {
private final V value;
private final X exception;
public static <V, X extends Throwable> Possibly<V, X> forValue(V v){
return new Possibly<V, X>(v, null);
}
public static <V, X extends Throwable> Possibly<V, X> forException(X x){
if (x == null) throw new NullPointerException();
return new Possibly<V, X>(null, x);
}
private Possibly(V v, X x){ value = v; exception = x; }
public X exception(){ return exception; }
public V value() throws X {
if (exception != null) throw exception;
return value;
}
}
然后你iterator()
将看起来像这样:
Iterator<Possibly<ParsedThingy, ThingyParseException>> parse() {
return new Iterator<Possibly<ParsedThingy, ThingyParseException>> {
public boolean hasNext(){ ... }
public void remove(){ ... }
public Possibly<ParsedThingy, ThingyParseException> next()
try {
ParsedThingy t = parseNext(); // throws ThingyParseException
return Possibly.forValue(t);
} catch (ThingyParseException e) {
return Possibly.forException(e);
}
}
};
}
种类繁琐,可以通过使东西少通用避免。
显示这种方法的问题(你必须处理循环体中的空值),并得到+1票。 – 2010-06-01 05:04:14
这种方法存在多个问题,但我会立即阐述。 – 2010-06-01 07:41:41