javaexceptionstaticunchecked-exception

Why JVM does not allow to throw Unchecked Exception from static block?


Why JVM does not allow to throw Unchecked Exception from static block? But it still allows them implicitly (e.g: calling method on null object).

Note: The question is more academic and not from real life issue.


Solution

  • You can throw it with a little hack but you will get ExceptionInInitializerError:

    Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

    static {
        try {
            throw new RuntimeException();
        }
        catch (IllegalArgumentException ignored){}
    }
    

    java.lang.ExceptionInInitializerError
    Caused by: java.lang.RuntimeException
    ...