Home > Net >  What is the optimal way to handle this type of exceptions?
What is the optimal way to handle this type of exceptions?

Time:10-02

This is a sample block from my code.

...
try {
    race.setDate(new Date(dateFormat.parse(entry[5]).getTime()));
    race.setTime(Time.valueOf(entry[6]));
    race.setFp1Date(new Date(dateFormat.parse(entry[8]).getTime()));
    race.setFp1Time(Time.valueOf(entry[9]));
    race.setFp2Date(new Date(dateFormat.parse(entry[10]).getTime()));
    race.setFp2Time(Time.valueOf(entry[11]));
    race.setFp3Date(new Date(dateFormat.parse(entry[12]).getTime()));
    race.setFp3Time(Time.valueOf(entry[13]));
    race.setQualiDate(new Date(dateFormat.parse(entry[14]).getTime()));
    race.setQualiTime(Time.valueOf(entry[15]));
    race.setSprintDate(new Date(dateFormat.parse(entry[16]).getTime()));
    race.setSprintTime(Time.valueOf(entry[17]));
} catch (ParseException e) {
    throw new RuntimeException(e);
}
...

Here every line in the try block can throw exception. According to my requirement if entry[i] is unparsable then the setter should set the value as null rather than throwing the exception. Putting every line in a try-and-catch block doesn't seem an optimal solution. How can I optimally handle this situation rather than checking the value of entry[i] in every line?

CodePudding user response:

Write a function which will catch a ParseException and return null:

    static <T> T parseOrNull(Supplier<T> parser) {
        try {
            return parser.get();
        } catch (ParseException e) {
            return null;
        }
    }

Then call it in each of your lines:

...
            race.setDate(parseOrNull(()  -> new Date(dateFormat.parse(entry[5]).getTime())));
...

CodePudding user response:

You can introduce new interface

interface Parser<T> {
    T parse(String value) throws ParseException;
}

then create helper function

    private static <T> void safeSet(Consumer<T> c, Parser<T> parser, String value){
        try {
            c.accept( parser.parse(value));
        } catch (ParseException e) {
            // log parse error
        }
    }

and use it in a following way:

       safeSet( race::setDate, x-> new Date(dateFormat.parse(x).getTime()), entry[5]);

Additional bonus you can reuse parsers:

       Parser<Date> dateParser = x -> new Date(dateFormat.parse(x).getTime());
       safeSet(race::setDate, dateParser, entry[5]);
       safeSet(race::setFp1Date, dateParser, entry[8]);
  • Related