Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DateTime, Unreachable catch block for ParseException

This is the method to parse the date object into a particular pattern. But it is giving error for the catch block saying it is unreachable and I can either remove the catch block or throw the exception directly. The reason I wanted catch block is to have visibility should there occur any error.

public static Date parseDate(Date a, String someFormat) {
    Date parsedDate = null;
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(someFormat);
    try {
        Instant instant = a.toInstant();

        LocalDate localDate =LocalDate.parse(dateFormat.format(instant), dateFormat);
        parsedDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    } catch (ParseException e) {
        logger.error(ExceptionUtils.getRootCauseMessage(e), e);
    }
    return parsedDate;
}
like image 455
Cursed Avatar asked Oct 24 '25 14:10

Cursed


1 Answers

The only checked exception that your try block throws is not a ParseException, which is what a SimpleDateFormat would throw, but a DateTimeParseException, which is what LocalDate.parse throws, and a DateTimeParseException is not a ParseException.

The compiler sees the catch block as unreachable because the ParseException is never thrown from the try block.

Just catch DateTimeParseException instead.

} catch (DateTimeParseException e) {

Note that because it's a RuntimeException, it's not absolutely necessary to catch it at all. But since you are already attempting to have "visibility", which is a good thing, and you're already attempting to catch an exception, just catch the correct exception type.

like image 190
rgettman Avatar answered Oct 26 '25 04:10

rgettman