有沒有處理任何方式 - 並繼續 - 在保持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