0

I have inherited the following java code, that gets the value of a property from a properties file:

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

The intended behavior in the above flow is that personName will either be retrieved from the properties file or will be returned as null if its not there, and handled accordingly.

However when the property is not there an exception is thrown in the getFileProperty() method (shown below).

How can I fix this to have the intended behavior?

getFileProperty():

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

Note - the getProperty() method being called in the code above is java utils getProperty method.

java12399900
  • 1,485
  • 7
  • 26
  • 56
  • `Optional` should not be used as a replacement for `if` statements. See https://stackoverflow.com/questions/23454952/uses-for-optional. – VGR Dec 31 '21 at 13:43

2 Answers2

1

You can use 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 
}
DEV
  • 1,607
  • 6
  • 19
1

You should wrap your code in a try catch block.

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

Edit: Alternatively provide a defaultValue to .getFileProperty()

String personName = this.properties.getFilePropertty("person.name", "NO_VALUE_FOUND");
if (!personName.equals("NO_VALUE_FOUND")) {
    // do something else
} else {
    // do something
}
gameshack_
  • 122
  • 9
  • ok thanks, so if an exception is thrown that means there is no property - so I need to handle it accordingly – java12399900 Dec 31 '21 at 10:58
  • It's always good practice to wrap functions that might throw an error in a try-catch block. I also just checked the documentation of the .getFileProperty() function and you can provide a defaultValue as a second argument. You could use that to properly handle what should happen if no key is found. I updated my answer. – gameshack_ Dec 31 '21 at 11:08