TryCatchFinallyReturn
public class TryCatchFinallyReturnTest {
public int test(){
try {
int i=1;
int j=2/i;
return 1;
}catch (Exception e){
e.printStackTrace();
return 2;
}finally {
return 3;
}
return 4;
}
public static void main(String[] args) {
int ret=new TryCatchFinallyReturnTest().test();
System.out.println(ret);
}
}
- 4是Unreachable statement,只有当try和catch的return二选一,且没有finally的return,才能编译通过,否则出现checked异常。
- try和catch和finally都有return的情况下,最后return的一定是finally的return,try和catch先执行到如果有return会缓存起来,如果finally有return就会覆盖。
版权声明:本文为zxcoder原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。