程序报错
catch有return
try {
//程序报错
int a = 1 / 0;
} catch (Exception e) {
return;
} finally {
System.out.println(1);
}
System.out.println(2);
//输出 1
catch无return
try {
//程序报错
int a = 1 / 0;
} catch (Exception e) {
} finally {
System.out.println(1);
}
System.out.println(2);
//输出 1 2
程序不报错
try有return
try {
//程序不报错
return;
} catch (Exception e) {
} finally {
System.out.println(1);
}
System.out.println(2);
//输出 1
try无return
try {
//程序不报错
} catch (Exception e) {
} finally {
System.out.println(1);
}
System.out.println(2);
//输出 1 2
总结
1.不管try catch是怎么样的,都会执行finally里代码;
2.是否输出2,要看在程序执行的路径上是否先有return,有则不输出2.。另外注意:try代码块里如果不报错,是不会执行catch里的代码的。
上面的列子可能不太全,各种可能写下来很罗嗦。大家可以自己试试。