【发布时间】:2015-04-19 17:09:06
【问题描述】:
假设我有以下内容:
class NegativeException extends RuntimeException {
}
class ZeroException extends NegativeException {
}
class Driver {
static boolean Marathon(int a) {
try {
if (a < 0)
throw new NegativeException();
else if (a == 0)
throw new ZeroException();
else if (a >= 42)
return true;
else
return false;
} catch (ZeroException e) {
System.out.println("Use natural number");
} finally {
System.out.println("One last thing");
}
System.out.println("All done.");
return false;
}
public static void main(String[] args) {
/* One last thing */
/* true */
System.out.println(Marathon(100));
System.out.println(Marathon(0));
System.out.println(Marathon(-5));
}
}
我想了解的是,为什么在使用我们的 main 方法的第一行时没有执行“All done”行? Marathon(100)
似乎finally 语句执行,然后输出return 语句。我知道finally 块将始终执行,无论发生什么。但是,我似乎无法理解 return 语句如何影响 try catch 块的流。尝试从try-cath-finally 块返回时,是否有一套适用的规则?
【问题讨论】:
-
"class ZeroException extends NegativeException" 嗯....记住,“扩展”意味着存在“是”关系。 “0 是负数”是不正确的。