public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
在这个问题中,try block 有 return 语句并抛出异常...... 它的输出是编译器错误....
我们知道 finally block 会覆盖 try/catch block 中的 return 或 exception 语句... 但是这个问题在 try block 中都有... 为什么输出错误?
最佳答案
因为您的 return
语句是不可访问的 - 执行流永远无法到达该行。
如果 throw
语句在 if
子句中,则 return
可能是可达的,错误就会消失。但在这种情况下,在此处设置 return
是没有意义的。
另一个重要注意事项 - 避免从 finally
子句返回。例如,Eclipse 编译器会在 finally
子句中显示有关返回语句的警告。
关于java - java中try block 中的return语句和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758503/