[英]Java: how to use try/catch block with return
如果列表為空並且我想要getLast()
則以下代碼將引發異常。 另外,我想使用throw/catch
-blocks對其進行修改,以使異常消息將出現在控制台上。
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
return list.getLast();
}
我的想法是:
double foo(double[] numbers, double n) {
LinkedList<Double> list = new LinkedList<Double>();
for (double x : numbers) {
if (x > 0 && x <= n && x % 2 != 0) {
list.add(x);
}
}
Collections.sort(list);
try{
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e);
}
return list.getLast();
}
這是正確的嗎? 異常被捕獲了嗎? 在throw/catch
-block之后的代碼呢? 它要執行嗎? 如果是,則將由return list.getLast();
再次引發異常return list.getLast();
?
我認為您正在尋找的是:
try {
return list.getLast();
} catch (Exception e){
System.out.println("caught: " + e); // consider e.printStackTrace()
throw new RuntimeException("Failed to get last", e);
}
}
如果list.getLast()
引發異常,它將被捕獲並打印消息。 然后,您將執行完全相同的操作並引發完全相同的異常。
如果您依賴於列表為空時拋出的異常,請考慮重新拋出該異常:
try {
return list.getLast();
} catch (Exception e) {
System.err.println("Caught: " + e);
throw e; // re-throw
}
// no "return" outside since we'll have thrown our previously caught error.
為什么要完全使用try / catch。 如果您只想確定列表是否為空,那么檢查list.size() != 0
怎么辦? 然后,如果為true或Double.Nan
,則返回list.getLast()
如果為false,則返回一條消息到控制台。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.