假设有以下代码:
java
public Object foo(String cmd) {
try {
return exe(cmd);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object goo(String cmd) {
try {
return exe(cmd);
} catch (Exception e) {
throwEx(e);
}
} //Missing return statement
public void throwEx(Exception e) {
throw new RuntimeException(e);
}
从表面看foo中的catch块和goo的catch块中都是抛出一个RuntimeException, 区别是goo调用的是将throw new RuntimeException(e)封装的方法, 但goo方法编译时会提示缺少返回值, 若改成下面的写法便可通过编译:
java
public Object goo(String cmd) {
try {
return exe(cmd);
} catch (Exception e) {
return returnEx(e);
}
}
public RuntimeException returnEx(Exception e) {
return new RuntimeException(e);
}
由此可得出结论:
对于有返回值的方法中的try...catch...块的所有路径都要有显示的return或throw, 编译器不会分析方法内部逻辑.
这是因为java编译器遵循静态路径分析(static path analysis) 的规则,编译器只依赖语法和方法签名来判断返回路径, 而不是去智能推断所有方法内部的实际行为。