Better way to continue after exceptions in java

Weishi Zeng :

Assuming I have to read from a file, and then construct a java object out of it.

PersonData p = new PersonData();
p.setName(readTokenAsString());
p.setAge(AgeConverter.createFromDateOfBirth(readTokenAsString()));  // this throws a checked exception if the date of birth is mal-formed.

//... a list of methods that throws exception as AgeConverter

Behavior I want: If one attribute has problem, just ignore it and keep process other attributes.

Solution I can think of:

try {
  p.setAge1(...);
} catch (Exception e) {
  //log and ignore
}

try {
  p.setAge2(...);
} catch (Exception e) {
  //log and ignore
}

//repeat for each attribute

Question:

Is there better way to do this to avoid repetition? Functional style maybe?

a) What's the best approach if I cannot modify PersonData class.
b) What's the best approach if I can rewrite PersonData class.

user10367961 :

Given your current declaration, I would do it as follows.

Define a @FunctionalInterface to which you can pass your I/O logic:

@FunctionalInterface
public interface CheckedSupplier<T> {
    T getValue() throws Exception;
}

Define an utility method that consumes the @FunctionaInterface:

public static final <T> T getValueWithDefault(CheckedSupplier<T> supplier, T defaultValue) {
    try {
        return supplier.getValue();
    } catch (Exception e){
        return defaultValue;
    }
}

Use the utility method as follows:

PersonData p = new PersonData();
p.setName(getValueWithDefault(() -> readTokenAsString(), "default"));
p.setAge(getValueWithDefault(() -> AgeConverter.createFromDateOfBirth(readTokenAsString()), 0));

This should do the trick regardless of weather you want modify the PersonData class or not.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97212&siteId=1