Java : ClassCastException with Examples
ClassCastException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most ClassCastException methods.
Summary
class Base {
}
class SubA extends Base {
}
class SubB extends Base {
}
final Base base = new SubA();
// Cast OK!
final SubA subA = (SubA) base;
// Cast NG!
try {
final SubB subB = (SubB) base;
} catch (ClassCastException e) {
System.out.println("ClassCastException!");
}
// Result
// ↓
//ClassCastException!
Constructors
ClassCastException ()
final var e = new ClassCastException();
System.out.println(e); // java.lang.ClassCastException
ClassCastException (String s)
final var e = new ClassCastException("abcde");
System.out.println(e); // java.lang.ClassCastException: abcde
System.out.println(e.getMessage()); // abcde
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- CancellationException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalArgumentException
- IllegalStateException
- IndexOutOfBoundsException
- NoSuchElementException
- NullPointerException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable