L
L
lafayette2011-01-30 18:02:00
Java
lafayette, 2011-01-30 18:02:00

Java: How to pass exception in singleton class constructor to getInstance()?

There is something like this code (in this case, non-working):

public class SingletonClass {
  public SingletonClass() throws Throwable {
    /* ... */
  }

  public static SingletonClass getInstance() throws Throwable {
    return SingletonHolder.instance;
  }

  private static class SingletonHolder {
    public static SingletonClass instance = new SingletonClass();
  }
}

Those. I need to pass a constructor exception to getInstance(), but since it is initialized statically (tried including through static { }), I can't set throws.
I hope I explained clearly :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
javax, 2011-01-30
@lafayette

In this case, no way.
Solutions
1. Use Spring for singletons (best)
2. Perverse - in the constructor, do a try{}catch{}(). If there is an exception, store it in another static variable. getInstance() will check - if the exception is saved - it will be thrown away, if not - it will go to the field with the instance and return it. But I wouldn't do that :)
3. Singleton initialization at the beginning of the program. In one place. Then you can not write getInstance () but use a public static field of the class
Seriously - if the singleton constructor can throw an exception - use Spring, Luke

O
Ololesha Ololoev, 2011-01-30
@alexeygrigorev

Why doesn't this code work?

public class ThrowSingleton {
  static public void main(String args[]) throws Throwable {
    SingletonClass.getInstance().toString();
    
  }
}

class SingletonClass {
  public SingletonClass() throws Throwable {
    throw new Exception();
  }

  private static SingletonClass instance;
  
  public static SingletonClass getInstance() throws Throwable {
    if (instance != null) {
      instance = new SingletonClass();
    }
    
    return SingletonClass.instance;
  }
}

I didn’t quite understand why to make a private subclass that holds the singleton.

A
apangin, 2011-01-31
@apangin

The first two options from here will suit you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question