处理null异常获取属性方法

时间:2018-08-23 20:15:46

标签: java

我有一个配置文件,正在通过java.util.Properties类读取。如果文件中没有属性,则getProperty()方法将返回null。如果配置文件中没有任何属性,我想抛出一个异常。那我该怎么办呢?需要最好的方法。

3 个答案:

答案 0 :(得分:4)

您可以将Properties实例包装在一个自定义类中,以添加以下附加逻辑:

public class MandatoryProperties{

   private Properties properties;

   public MandatoryProperties(Properties properties){
       this.properties = properties;
   }

   public String getProperty(String key){
      String value = properties.getProperty(key);
      if (value == null){
          throw new RuntimeException(...);
      }
      return value;
   }
}

并将其用作:

MandatoryProperties properties = new MandatoryProperties(properties);
String value = properties.getProperty("aKey");

此处示例抛出未经检查的异常。如果您的用例更适合,请使用检查后的异常。

答案 1 :(得分:0)

您可以使用关键字throw来完成此操作。

您可以引发必须捕获或引发的已检查异常,也可以引发不必捕获的运行时异常。

语法如下:

if (null == getProperty("Propertyname")) {
    throw new RuntimeException("myMessage");
}

您还可以通过创建扩展Exception的类来创建自己的Exception。

答案 2 :(得分:0)

我将基于答案on davidxxx's one,但如果我从Properties继承我的课程,就会变得更加懒惰。

public class MandatoryProperties extends java.util.Properties {
    @Override
    public String getProperty(String key) {
        String value = super.getProperty(key);
        if (value == null){
           throw new RuntimeException("Unknown property " + key);
        }
        return value;
    }
}

这需要更少的代码,并允许您将其声明为Properties

请注意,在某些情况下,“包装” Properties实例可能会很有趣。