A better way to continue after an exception in Java… here is a solution to the problem.
A better way to continue after an exception in Java
Let’s say I have to read from a file and then construct a java object from 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
The behavior I want: If there is a problem with one property, ignore it and move on to the others.
I can think of a solution:
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 a better way to avoid duplication? Maybe functional style?
a) If I can’t modify the PersonData
class, what’s the best approach.
b) If I could override the PersonData
class, what would be the best approach.
Solution
Given your current statement, I will proceed as follows.
Define an @FunctionalInterface
to which you can pass I/O logic:
@FunctionalInterface
public interface CheckedSupplier<T> {
T getValue() throws Exception;
}
Define a practical method that uses @FunctionaInterface
:
public static final <T> T getValueWithDefault(CheckedSupplier<T> supplier, T defaultValue) {
try {
return supplier.getValue();
} catch (Exception e){
return defaultValue;
}
}
The practical method used is as follows:
PersonData p = new PersonData();
p.setName(getValueWithDefault(() -> readTokenAsString(), "default"));
p.setAge(getValueWithDefault(() -> AgeConverter.createFromDateOfBirth(readTokenAsString()), 0));
This solves the problem whether you want to modify the PersonData
class or not.