10

Possible Duplicate:
How to handle a static final field initializer that throws checked exception

In this example, I get the error The blank final field myClass may not have been initialized:

private final static MyClass myClass; // <-- error

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        // log
    }
}

In that example, I get the error The final field myClass may already have been assigned:

private final static MyClass myClass;

static {
    try {
        myClass = new MyClass(); // <-- throws exception
        myClass.init();
    } catch (Exception e) {
        myClass = null; // <-- error
        // log
    }
}

In there any solution to that issue?

Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252
  • Can your `MyClass` constructor throw an exception? Or is it `init()` method that can throw exception? – Rohit Jain Jan 30 '13 at 08:41
  • i think it's the initialize method that can throw, right? Because in that case, myClass can have an assigned value in the catch block. – kutschkem Jan 30 '13 at 08:43
  • Let's says the constructor can throw an exception too. In fact, it's an example that illustrates the issue I ran into with another piece of code. – sp00m Jan 30 '13 at 08:49

3 Answers3

14
private final static MyClass myClass;

static {
    MyClass my;
    try {
        my = new MyClass();
        my.init();
    } catch (Exception e) {
        my = null;
        // log
    }
    myClass = my; //only one assignment!
}
kutschkem
  • 7,826
  • 3
  • 21
  • 56
10

Here's a solution :

private final static MyClass myClass = buildInstance();

private static MyClass buildInstance() {
    try {
        MyClass myClass = new MyClass();
        myClass.init();
        return myClass;
    } catch (Exception e) {
        return null;
    }
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

If your class is final it can't change values once it is initialised. What you are doing in the second snippet is that you are first assigning it to new MyClass() and then if an Exception is thrown in init() you then change it to null.

This is not allowed. If new MyClass() does not throw an Exception why don't you put it at the top line?

Warning though, that if init() throws an Exception, you will still have an unintialised instance of MyClass. It doesn't seem that the way you're working with this class matches the way its designed to work.

jbx
  • 21,365
  • 18
  • 90
  • 144