Java : DateTimeException with Examples
DateTimeException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most DateTimeException methods.
Summary
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)
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)
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
- Get the current time
- Basics of Date and Time
- Don't use the legacy Date and Calendar classes, use new APIs instead
- API Examples
- Calendar
- ChronoLocalDate
- ChronoLocalDateTime
- ChronoZonedDateTime
- Clock
- Date
- DateTimeParseException
- DayOfWeek
- Duration
- Era
- Instant
- InstantSource
- JapaneseDate
- LocalDate
- LocalDateTime
- LocalTime
- Month
- MonthDay
- OffsetDateTime
- OffsetTime
- Period
- Temporal
- TemporalAccessor
- TemporalAdjuster
- TemporalAdjusters
- TimeZone
- Year
- YearMonth
- ZonedDateTime
- ZoneId
- ZoneOffset