Page 1 of 1

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

Posted: Thu Feb 16, 2017 2:51 am
by atrofimov
Hi there,
I wonder why this will not compile:
public class X {
static {
throw new NullPointerException();
}
}

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

Posted: Thu Feb 16, 2017 3:10 am
by admin
It should compile. The answer should be changed to ExceptionInInitializerError.
Fixed.
thank you for your feedback!
Paul.

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

Posted: Thu Mar 02, 2017 1:19 pm
by jankur
Hi, probably this question is ambiguous - in fact the Oracle compiler 1.8.0_121 for Linux refuses to compile the code because of the line "throw new NullPointerException();":
X.java:2: error: initializer must be able to complete normally
static {
^
1 error
This ambiguity probably could be removed if the code were changed for example as follows:

Code: Select all

public class X {
static {
problem();
}
static void problem() { throw new NullPointerException(); }
}
or

Code: Select all

public class X {
static String str;
static {
int len = str.length();
}
}
The quoted code snippets are compiled by aforementioned compiler without any errors, and they cause the expected ExceptionInInitializerError at run time.

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

Posted: Thu Mar 02, 2017 9:30 pm
by admin
You are right. I was mistaken. I am not sure why I thought it should compile. It doesn't compile on Windows compiler either. The original answer was correct. I have changed it back.

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


thank you for your feedback!
Paul.