Search code examples
javastatic-initialization

How are exceptions propagated by static blocks?


static {
    MessageDigest d;
    try {
        d = java.security.MessageDigest.getInstance("MD80"); <-- MD80 is no valid algorithm
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    hasher = d;
}

JVM will automatically execute these static initialiation statements when the class is loaded into JVM. That means, runtimeexception exception was thrown at load time.

Now, if I run such a class ( via eclipse ) I get a flood of exceptions originating from static blocks in the console.

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: java.security.NoSuchAlgorithmException: MD8 MessageDigest not available
    at BloomFilter.<clinit>(BloomFilter.java:86)
Caused by: java.security.NoSuchAlgorithmException: MD8 MessageDigest not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:142)
    at java.security.Security.getImpl(Security.java:659)
    at java.security.MessageDigest.getInstance(MessageDigest.java:129)
    at BloomFilter.<clinit>(BloomFilter.java:84)

But, here is the doubt. This exception was thrown at 'load time'. How was it displayed at runtime in the console ? Was this exception thrown and stored somewhere between 'load' and 'runtime' ?

Basically I am looking to understand what happens between 'loadtime and runtime' once the exception has been thrown in static block ?


Solution

  • There is no such thing as "load time" - there is only "runtime". When the JVM starts, it determines which classes it needs to load; static initializes are executed whenever they need to be; for example right after loading the class.