Answer the question
In order to leave comments, you need to log in
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();
}
}
Answer the question
In order to leave comments, you need to log in
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
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question