I want to parse text on a date. However, there is no guarantee that the text has the desired format. It can be 2012-12-12either 2012or or even .
I'm currently on the way to nested try-catch blocks, but this is not a good direction (I suppose).
LocalDate parse;
try {
parse = LocalDate.parse(record, DateTimeFormatter.ofPattern("uuuu/MM/dd"));
} catch (DateTimeParseException e) {
try {
Year year = Year.parse(record);
parse = LocalDate.from(year.atDay(1));
} catch (DateTimeParseException e2) {
try {
// and so on
} catch (DateTimeParseException e3) {}
}
}
What is an elegant solution to this problem? Is it possible to use Optionalthat is absent in case of exception during the assessment? If so, how?
source
share