Skip to content

Instantly share code, notes, and snippets.

@tzachz
Created September 1, 2015 12:59
Show Gist options
  • Save tzachz/20c5c0dc2520c641df6d to your computer and use it in GitHub Desktop.
Save tzachz/20c5c0dc2520c641df6d to your computer and use it in GitHub Desktop.
Java behavior when static constructor throws exception
public class StaticClass {
static {
throwsException();
}
private static void throwsException() {
throw new RuntimeException("bam!");
}
public static int SOMETHING = 0;
}
public class StaticClassTest {
@Test
public void testFailedStaticInitializer() throws Exception {
tryAccessing(); // prints: java.lang.ExceptionInInitializerError
tryAccessing(); // prints: java.lang.NoClassDefFoundError: Could not initialize class com.kenshoo.kripke.scoresources.StaticTestClass
tryAccessing(); // prints: java.lang.NoClassDefFoundError: Could not initialize class com.kenshoo.kripke.scoresources.StaticTestClass
}
private void tryAccessing() {
try {
System.out.println(StaticClass.SOMETHING);
} catch (Throwable e) {
System.out.println(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment