Catching exceptions from static fields in the main class

I never thought about this before, but looked at the following code

public class SomeJavaProgram {

    private static String runMe() {
        throw new RuntimeException("hi tadsfasdf");
    }
    private static String name = runMe();

    public static void main(String[] args) {
        System.out.println("hi there.");
    }
}

I had never done such statics before basically, but then I introduced scala, and if you have subclasses that start adding defs, exceptions can be thrown before main is even called.

So, in java (not scala), is there any way to catch these exceptions (if I am a superclass and the subclasses ultimately have a static field that throws an exception or a static initializer block) .... how can I catch all this?

Of course, I rely on one single definition that does not drop, which is

private Logger log = createLoggerFromSomeLoggingLib();

But after that, ideally, I would like all exceptions to be written to the log file, not to stderr.

, , stderr/stdout .

+4
1

:

private static String name;

static {
    try {
        name = runMe();
    } catch (RuntimeException e) {
        // handle
    }
}
+4

All Articles