Handle NullValueInNestedPathException I am looking for a elegant solution to this. I am new to Spring framework. I have a method:

public String getStringProperty(String property) {
        Object value = SomeWrapper.getPropertyValue(property);
        return (value != null) ? String.valueOf(value) : "";
    }


The immediate upstream method is:

public String getValueForHeader(String header) {
        return getStringProperty(LOOKUP_TABLE.get(header));
    }


Where LOOKUP_TABLE is an ImmutableMap (google guava). An example representation of it:

private final ImmutableMap&lt;String, String&gt; LOOKUP_TABLE = ImmutableMap.&lt;String, String&gt;builder()
            .put(LogHeaders.Phone, "Person.phone")
            .put(LogHeaders.Address, "Person.personal.address")
            .put(LogHeaders.Email, "Person.billing.contact.primary.email")
            .put(LogHeaders.Ip, "Person.ip")            
            .build();


So, when I call getStringProperty method with property "Person.billing.contact.primary.email" I get a "" String. My aim here is to return empty String when some property does not exist. For example if "Person.billing.contact.primary.email" does not have "email" set in address an empty String is returned. Now if "contact" or "primary" is not set I would get a NullValueInNestedPathException but I should return an empty String.

One way to deal with this is to introduce the try catch lock in this method and have the catch block return empty string. 

public String getStringProperty(String property) {
    try {
        Object value = transactionWrapper.getPropertyValue(property);
        return (value != null) ? String.valueOf(value) : "";
    } catch (NullValueInNestedPathException e) {
        return "";
    } catch (NotReadablePropertyException nr) {
        LOGGER.error("Invalid property {} ", property);
        return "!invalid property!";
    }
}


The NotReadablePropertyException is to warn me when I am trying to get some property which does not exist (or getter for that property is not readable).

The other solution could be to throw same exception and let methods upstream worry. 

Is there some alternative, elegant way to handle this inside my getStringProperty() method ?
Returning "" is reasonable, since that is what you want to use as the default value.

Returning the special value "!invalid property!" to indicate an error might be allowable only in the following limited circumstance:


This is view-layer code, not your model, not middleware, not an API, and
You actually want that special string to appear in the UI as a placeholder, and
The placeholder text is to be presented in the normal font and color.


If any of those conditions is not applicable, then the special string is absolutely inappropriate. That is precisely what exceptions are for — exceptional cases. If you present exceptional cases as if they were legitimate data, then you end up with bugs like this one, where a person whose name is Null causes grief.