Singleton构造函数中抛出异常如何处理?

我比较喜欢的Singleton方式是
class singleton {
private static singleton instance = new singleton();
private singleton() {
}

public static singleton getInstance() {
return instance;
}
}

OK,问题来了,如果这里的私有构造函数抛出异常该怎么处理?
这种写法肯定就是不行了,我尝试将instance该在static区内初始化,也就是这么写。
private static singleton instance;
static {
try {
instance = new singleton();
} catch (Exception e) {
instance = null;
}
}

static区中内容的执行是在这个加载的时候进行的,但是对于普通的一个应用,我通常只会直接调用getInstance,而并不去考虑这个类初始化时出了什么问题。换句话说,类初始化的异常并没有抛出来,我的程序无法对其进行跟踪。只有当我调用这个类的对象抛出NullPointerException时我才知道,这个类初始化出了问题,前提还是这个类是我写的,我对其运作很清楚。如果拿给别人用,就很难找到其中的问题了。

别告诉我把初始化代码拿出来专门做一个初始化的方法,我最初的代码就是从那里过来的。

百思不得其解,故来向大侠们请教。

可否这样:


....

public static singleton getInstance() throws Exception {
if (instance == null) throw new Exception
return instance;
}

...

当别人调用getInstance()时 只要就可以catch Exception了

产生静态实例那块用工厂,从工厂那里抛例外,结构比较清晰一些

可以使用懒汉式单例

public class Singleton {
private static instance = null;

private Single() throws Exception {
// your code here
}

public static synchronized Singleton getInstance() throws Exception {
if( instance == null ) {
instance = new Singleton();
}
return instance;
}
}

}

可以使用懒汉式单例

public class Singleton {
private static instance = null;

private Single() throws Exception {
// your code here
}

public static synchronized Singleton getInstance() throws Exception {
if( instance == null ) {
instance = new Singleton();
}
return instance;
}
}