Java : DateTimeException with Examples

DateTimeException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most DateTimeException methods.


Summary

Exception used to indicate a problem while calculating a date-time.

Class diagram

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

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

// Result
// ↓
//-- OK --
//date : 2100-12-31
//-- NG --
//DateTimeException! : Invalid value for DayOfMonth (valid values 1 - 28/31): 40
System.out.println("-- OK --");
final var time1 = LocalTime.of(12, 30);
System.out.println("time : " + time1);

System.out.println("-- NG --");
try {
    final var time2 = LocalTime.of(12, 60);
} catch (DateTimeException e) {
    System.out.println("DateTimeException! : " + e.getMessage());
}

// Result
// ↓
//-- OK --
//time : 12:30
//-- NG --
//DateTimeException! : Invalid value for MinuteOfHour (valid values 0 - 59): 60

Constructors

DateTimeException (String message)

Constructs a new date-time exception with the specified message.

final var e = new DateTimeException("abcd");
System.out.println(e); // java.time.DateTimeException: abcd
System.out.println(e.getMessage()); // abcd

DateTimeException (String message, Throwable cause)

Constructs a new date-time exception with the specified message and cause.

final var cause = new DateTimeException("XYZ");
final var e = new DateTimeException("abcd", cause);

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

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

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