结论:
①就算之前return,finally也会执行
②finally的计算结果不影响之前的return值
③finally的return值一定是最后的返回结果,因此将return放入finally编译器会警告。
static int testReturn() {
int res = 0;
File file = new File("test");
try {
Scanner in = new Scanner(file);
return res = 1;
} catch (FileNotFoundException e) {
System.out.println("Catch");
return res = 2;
} finally {
System.out.println("finally");
res *=10;
// return res;
}
}
输出结果:
Catch
finally
return结果:20