【问题标题】:Java - code will always throw a Null Pointer Exception when no Property is present?Java - 当没有属性时,代码总是会抛出空指针异常?
【发布时间】:2021-12-31 10:25:28
【问题描述】:

我继承了以下 java 代码,它从 properties file 获取 property 的值:

    String personName = this.properties.getFilePropertty("person.name");
    if (personName != null) {
       // do something else
    } else {
        // do something
    }

上述流程中的预期行为是,personName 将从属性文件中检索,或者如果不存在则返回为 null,并进行相应处理。

但是,当该属性不存在时,getFileProperty() 方法中会引发异常(如下所示)。

我怎样才能解决这个问题以获得预期的行为?

getFileProperty():

            public String getFileProperty(String name) throws SystemPropertiesException {
            
            return Optional.ofNullable( this.properties.getProperty(name, null) )
            .orElseThrow(()->new PropertiesException("Can not get property!"));
            
             }

注意——上面代码中调用的getProperty()方法是java utils getProperty方法。

【问题讨论】:

标签: java string exception properties optional


【解决方案1】:

您应该将代码包装在 try catch 块中。

try {
    String personName = this.properties.getFileProperty("person.name");
    // do something else
} catch (PropertiesException exception) {
    // do something
}

编辑:或者为.getFileProperty()提供一个默认值

String personName = this.properties.getFilePropertty("person.name", "NO_VALUE_FOUND");
if (!personName.equals("NO_VALUE_FOUND")) {
    // do something else
} else {
    // do something
}

【讨论】:

  • 好的,谢谢,所以如果抛出异常意味着没有属性 - 所以我需要相应地处理它
  • 在 try-catch 块中包装可能引发错误的函数始终是一个好习惯。我还刚刚检查了 .getFileProperty() 函数的文档,您可以提供一个 defaultValue 作为第二个参数。如果没有找到密钥,您可以使用它来正确处理应该发生的情况。我更新了我的答案。
【解决方案2】:

你可以使用try catch

try{
    String personName = this.properties.getFilePropertty("person.name");
    //if it's not null there will be no exception so you can directly use the personName 
    
}catch(SystemPropertiesException ex){
    //else there is an exception to handle here 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2020-08-10
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多