[英]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.