为什么以后执行静态块?

Thi*_*ker 4 java static

PS:

This question has been edited a few times as my previous code doesn't demonstrate the problem. There are some answers which may not make perfect sense against the edited question

我有一个名为的公共类 Son.java

package com.t;

public class Son extends Father {

    static int i;

    static {
        System.out.println("son - static");
        i = 19;
    }

    {
        System.out.println("son - init-block"); 
    }

    public static void main(String[] args) {
        //Son s = new Son();
        int a[] = new int[2];
        System.out.println(a[5]);
    }

}

class Father {

    static {
        System.out.println("f - static");
    }
    {
        System.out.println("f - init-block");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我第一次运行程序时:

输出是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at com.t.Son.main(Son.java:19)
f - static
son - static
Run Code Online (Sandbox Code Playgroud)

后来当我运行这个程序时(输出顺序是random)

输出是:

f - static
son - static
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at com.t.Son.main(Son.java:19)
Run Code Online (Sandbox Code Playgroud)

我已经读过static在执行类时会执行块.

但为什么异常首先出现在那里然后执行静态块?

Eclipse也用它来运行我的程序.有人可以解释一下吗?

Kep*_*pil 10

首先不会发生异常,您只是首先看到异常的打印输出.

如果首先发生异常,您将永远不会看到输出的其余部分.

这样做的原因是你有两个System.err(从你的例外)和System.out你的程序输出.这些打印到屏幕的顺序没有定义,因此您可以按不同的顺序获取它们.