我正在解决一些Java任务,并且对此有问题:
What is the output of this code?
public class Test {
public static int test(int i) {
try {
if (i == 0) throw new Exception();
return i;
} catch (Exception e) {
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
System.out.print(test(0));
System.out.print(test(3));
}
}
该代码的正确答案是22。
有人可以向我解释为什么22吗?为什么不12?
谢谢!
finally
块被保证运行,无论是否抛出Exception
。在这里,您将在2
块中返回finally
,因此您的方法必须总是返回2。
在0
的情况下,您在体内抛出异常,输入catch块,然后返回一个,然后返回finally块(返回两个)。对于3
,返回三个,输入finally块并返回两个。因此,您的输出为22
。