Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1031 :

Posted: Wed Jul 01, 2020 4:21 am
by Ardaks
Hi admin. Could you please explain, why ExceptionInInitializerError is not thrown in the forth point?

Re: About Question enthuware.ocajp.i.v8.2.1031 :

Posted: Wed Jul 01, 2020 4:24 am
by admin
ExceptionInInitializerError can be thrown when the code is run. But before you can run the code, it has to be compiled. Option 4 fails during compilation, which means, you can't run it. So, an ExceptionInInitializerError will not be thrown.

Re: About Question enthuware.ocajp.i.v8.2.1031 :

Posted: Thu Jul 10, 2025 6:31 pm
by arty9608
Hi, just incase there's anyone wondering:
Compiling the fourth points results in the following compile time error:

------------------------------
X.java:16: error: initializer must be able to complete normally
static {
^
1 error
------------------------------

Java essentially sees that the static block will never complete and flags the error.

If we modify the code a little and trick the compiler into thinking that the block might execute normally, in that case we can get the ExceptionInInitializerError:

-------------------------------
public class X {
static {
if (true) // Compiler thinks this may or may not be true.
throw new NullPointerException(); // This is okay!
}

public static void main(String[] args) {

}
}
-------------------------------