Java : DateTimeParseException with Examples

DateTimeParseException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most DateTimeParseException methods.


Summary

An exception thrown when an error occurs during parsing.

Class diagram

System.out.println("-- OK --");
final var date1 = LocalDate.parse("2100-12-31");
System.out.println("date : " + date1);

System.out.println("-- NG --");
try {
    final var date2 = LocalDate.parse("2100-12-40");
} catch (DateTimeParseException e) {
    System.out.println("DateTimeParseException! : " + e.getMessage());
}

// Result
// ↓
//-- OK --
//date : 2100-12-31
//-- NG --
//DateTimeParseException! : Text '2100-12-40' could not be parsed:
// Invalid value for DayOfMonth (valid values 1 - 28/31): 40

Constructors

DateTimeParseException (String message, CharSequence parsedData, int errorIndex)

Constructs a new exception with the specified message.

final var e = new DateTimeParseException("abcd", "2100-12-40", 8);
System.out.println(e); // java.time.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8

DateTimeParseException (String message, CharSequence parsedData, int errorIndex, Throwable cause)

Constructs a new exception with the specified message and cause.

final var cause = new DateTimeException("XYZ");
final var e = new DateTimeParseException("abcd", "2100-12-40", 8, cause);

System.out.println(e); // java.time.format.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8

System.out.println(e.getCause()); // java.time.DateTimeException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

Methods

int getErrorIndex ()

Returns the index where the error was found.

final var e = new DateTimeParseException("abcd", "2100-12-40", 8);
System.out.println(e); // java.time.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8

String getParsedString ()

Returns the string that was being parsed.

final var e = new DateTimeParseException("abcd", "2100-12-40", 8);
System.out.println(e); // java.time.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page