1.构造函数中的异常
在一个项目中多个方法中都用到了外部的配置文件,所以想写一个单例模式来读取一次外部配置文件,而不是每次用的时候都读一次.
代码如下:
//实际本质上就是只返回一个SingletonProps 实例.
public class SingletonProps {
private Properties properties;
private SingletonProps() throws IOException {
InputStream in = this.getClass().getResourceAsStream("/System.properties"); //注意,这里不能改成参数的形式!!!,因为会初始化一次.
properties = new Properties();
properties.load(in);
}; //私有
//静态私有内部类
private static class SingletonHolder {
private static final SingletonProps singleton_Props =new SingletonProps();
}
public static final SingletonProps getInstance() {
return SingletonHolder.singleton_Props; //无论什么时候调用都只返回一个singletonProps 类的实例
}
public Properties getProperties() throws IOException{
return properties;
}
}
问题出现在静态私有内部类中初始化静态成员变量时.因为外部类的构造函数会抛出异常.
而在初始化静态成员变量时是不能抛出异常的,一旦出现那就是出现了错误,所以编译器不会让这里的代码通过编译.在运行是如果在初始化静态成员变量时出现运行时异常,会抛出ExceptionInInitializerError.
后来我的解决方法是:以下或者使用枚举模式实现 http://www.cnblogs.com/predisw/p/4763784.html
//实际本质上就是只返回一个SingletonProps 实例.
public class SingletonProps {
private Properties properties;
private InputStream in;
private SingletonProps() {
in = this.getClass().getResourceAsStream("/System.properties"); //注意,这里不能改成参数的形式!!!,因为会初始化一次.
properties = new Properties();
}; //私有
//静态私有内部类
private static class SingletonHolder {
private static final SingletonProps singleton_Props =new SingletonProps();
}
public static final SingletonProps getInstance() {
return SingletonHolder.singleton_Props; //无论什么时候调用都只返回一个singletonProps 类的实例
}
public Properties getProperties() throws IOException{
properties.load(in);
return properties;
}
}
关于是否应该在构造函数中抛出异常的讨论:
http://stackoverflow.com/questions/6086334/is-it-good-practice-to-make-the-constructor-throw-an-exception
比较认可的说法是:
在构造函数中是抛出异常是一种合理的方法以至于让调用者知道为什么没有构造成功,例如参数不正确,之类;但是要抛出明确的异常,不要抛出Exception 之类的不明确的.
来源:https://www.cnblogs.com/predisw/p/4763513.html