Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to continue after exceptions in java

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.

like image 349
Weishi Z Avatar asked Oct 21 '25 17:10

Weishi Z


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!