Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Create static class member whose constructor could throw an exception

I have a static setter that is used to set all instances of MyClass:

public class MyClass {  
        ....
    protected static final Setter setter = new Setter();
        ...
}

However this does not compile since the setter constructor throws an exception:

public class Setter {

    public Setter() throws FileNotFoundException {
             ....
    }
}

How can I work around this?

like image 289
sixtyfootersdude Avatar asked Jul 14 '10 14:07

sixtyfootersdude


1 Answers

The ExceptionInInitializerError is designed for exactly this purpose. Here's a cite of relevance from the linked Javadoc:

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.

Wrap the assignment in a static initializer block and handle accordingly.

public class MyClass {  
    protected static final Setter setter;

    static {
        try { 
            setter = new Setter();
        } catch (FileNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
}
like image 134
BalusC Avatar answered Oct 04 '22 20:10

BalusC