ClassCastException

ClassCastException

This is an unchecked exception as it is a subclass of RuntimeException. We know in exception handling, all the subclasses of RuntimeException are known as unchecked exceptions.

Following is the hierarchy.

Object –> Throwable –> Exception –> RuntimeException –> ClassCastException

Complete exception hierarchy is available at Hierarchy of Exceptions – Checked/Unchecked Exceptions.

As the name indicates, this exception is raised by JVM when it is unable to cast two objects which is done by the programmer against the rules of Java casting. Let us explain through a program.

ClassCastException

r = (Rose) f;

In the above statement, Flower object f is explicitly casted to Rose and assigned. It compiles smoothly, but at execution time throws ClassCastException. Observe the screenshot. Why the JVM throws? What illegal operation is done in the code?

We know earlier the rules of object casting. The rule says "before doing explicit casting, there must be implicit casting done earlier". But in the above code it is not done. Then how to correct the code? Just put the following statement before (in the code, remove the comments).

f = r;

In the above statement, a subclass object is assigned to super class object and this casting is done implicitly. This must be done before explicit casting is made. In the above program, it is not done (placed in comments). For this, the JVM reacts by throwing "ClassCastException".

Leave a Reply

Your email address will not be published. Required fields are marked *