简体   繁体   English

从主类中的静态字段中捕获异常

[英]Catching exceptions from static fields in the main class

I never really thought about this before but looking 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 never did statics like this in a main before but then I entered scala, and if you have subclasses that start adding defs, exceptions can be thrown before main is even called. 我以前从未在main中执行过这样的静态,但之后我进入了scala,如果你有继续添加defs的子类,则在调用main之前可以抛出异常。

So, in java(not scala), is there a way to catch these exceptions(if I am the superclass and subclasses end up having a static field that throws an exception or static initializer block)....how can I catch all these? 所以,在java(而不是scala)中,有没有办法捕获这些异常(如果我是超类和子类最终有一个抛出异常或静态初始化程序块的静态字段)....我怎么能抓住所有这些?

I of course do rely on ONE single definition not throwing which is the 我当然要依靠一个单一的定义而不是扔掉哪个

private Logger log = createLoggerFromSomeLoggingLib();

But after that, ideally I would want all exceptions to be logged to the logged file rather than stderr. 但在那之后,理想情况下我希望将所有异常记录到记录的文件而不是stderr。

That said, I am glad I have always kept the stderr/stdout files along with my logging files now. 也就是说,我很高兴我现在始终将stderr / stdout文件与我的日志文件一起保存。

Use the static initializer: 使用静态初始化程序:

private static String name;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM