• java 基础之异常


    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 之类的不明确的.

  • 相关阅读:
    SmartDb代码修改
    windows下Nginx+RTMP部署
    嵌入式linux下获取flash分区大小
    (转)Qt添加windows开机自启动
    (转)交叉编译lrzsz
    关于海思SDK在Ubuntu下安装错误问题
    电总协议串口调试助手
    使用git将本地仓库上传到远程仓库(转)
    c++中包含string成员的结构体拷贝导致的double free问题
    59. 可变参数
  • 原文地址:https://www.cnblogs.com/predisw/p/4763513.html
Copyright © 2020-2023  润新知