为什么这个 java 代码没有捕捉到所有异常

Why this java code does not catch all the exceptions

我不明白为什么这段代码只抛出 NullPointerException。

(有 System.getProperty("") 代码抛出 IllegalArgumentExceptionx=x/0; 抛出 ArithmeticException: / by zero 但在第一条语句中,抛出异常并忽略其他异常,除了while 循环)

public static void main(String[] a) {


        try {
            String current = System.getProperty(null);
            String current2 = System.getProperty("");
            int num=2;
            num=num/0;
            System.out.println(String.valueOf(num));
        }
        catch(Exception e){

           System.out.println(e.toString());

        }   

        int i = 0;
        while (i < 10) {
            i++;
            System.out.println(i);
        }

        /**/
    }

为什么在计算完所有表达式并打印出它们的异常后代码才继续执行?

输出为:

java.lang.NullPointerException: key can't be null
1
2
3
4
5
6
7
8
9
10

代码在抛出第一个异常时退出到catch块,不执行try块中剩余的代码

Java 中的异常处理根本不是这样。异常的抛出会传播到调用堆栈中第一个符合条件的 catch 块,在本例中是您的 catch Exception(..) 块。块运行后,执行在 catch 底部 处恢复。

在抛出 Exception 的行之后的行继续执行是没有意义的。您将无法保证对象状态,并且可以说这会使调试变得更加困难。但是无论如何您都不应该使用异常处理作为流程控制。有关详细信息,请参见此处:http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl