为什么此Java代码的正确输出是22?不是十二? [重复]

问题描述 投票:0回答:1

我正在解决一些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?

谢谢!

java exception output
1个回答
0
投票

finally块被保证运行,无论是否抛出Exception。在这里,您将在2块中返回finally,因此您的方法必须总是返回2。

0的情况下,您在体内抛出异常,输入catch块,然后返回一个,然后返回finally块(返回两个)。对于3,返回三个,输入finally块并返回两个。因此,您的输出为22

© www.soinside.com 2019 - 2024. All rights reserved.