[英]handle exceptions in stream java 8
我有一個字符串:
"1, 2, 3 , -4"
它被“,”分割。 我有一個函數可以將一個數字轉換為一個可以正常工作的枚舉類型。 我想使用 java 8 將此字符串轉換為枚舉對象列表。
Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
.map(s -> {
try {
return this.getEnumObject(Integer.valueOf(s), f.class);
}
catch (NoEleException e) {
e.printStackTrace();
}
})
.collect(Collectors.toList());
這給了我一個錯誤:
missing return type.
我怎么能修好呢?
目前,如果發生異常,則不會返回任何結果,因此會出現編譯錯誤。 您需要在catch
塊之后返回一個值。
基本上是管理這個的方法:
在第一種情況下,我們使用 Optional 在出錯時將某些內容放入流中,然后在流中進一步管理這些空值:
pattern.splitAsStream(str)
.map(s -> {
try {
return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
}
catch (NoEleException e) {
e.printStackTrace();
return Optional.empty();
}
})
.filter(Optional::isPresent) // remove empty optionals
.map(Optional::get) // unwrap them
.collect(Collectors.toList());
在第二種情況下,流停止,然后您可以嘗試捕獲 RuntimeException 並解開原始異常:
pattern.splitAsStream(str)
.map(s -> {
try {
return Optional.of(this.getEnumObject(Integer.valueOf(s), f.class));
}
catch (NoEleException e) {
e.printStackTrace();
throw new RuntimeException(e); // stop the stream
}
})
.collect(Collectors.toList());
您可以創建像 MissingElement 這樣的 Null 對象,在 catch 中返回它,然后在 map 之后將其過濾掉。
如果您確定這不會發生,您可以在收集之前在 catch 中返回 null 並過濾非 null:
Pattern pattern = Pattern.compile(", ");
List<f> fList = pattern.splitAsStream(str)
.map(s -> {
try {
return this.getEnumObject(Integer.valueOf(s), f.class);
}
catch (Exception e) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.