java.lang. ClassCastException In Java
ClassCastException In Java: In this post, we are going to discuss ClassCastException. A class cast exception is thrown by Java when you try to cast an Object of one data type to another. Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
ClassCastException In Java
As you can see in the above pic ClassCast-Exception exception extends the class RuntimeException and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
java.lang.classcastexception In Java:
An object can be automatically upcasted to its superclass type. You need not mention class type explicitly. But, when an object is supposed to be downcasted to its subclass type, then you have to mention class type explicitly. In such a case, there is a possibility of occurring class cast exception. Most of the time, it occurs when you are trying to downcast an object explicitly to its subclass type.
package co.java.exception; public class ClassCast_Exception < public static void main(String[] args) < Object obj=new Object(); int i=(int) obj; System.out.println(i); >>
Lets Run The Above Program:
When we run the above program we got the below error:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer at co.java.exception.ClassCastException.main(ClassCast-Exception.java:8)
Let’s take another example:
package co.java.exception; class Parent < public Parent() < System.out.println("An instance of the Parent class was created!"); >> final class Child extends Parent < public Child() < super(); System.out.println("An instance of the Child class was created!"); >> public class ClassCast-ExceptionExample < public static void main(String[] args) < Parent p = new Parent(); Child ch = new Child(); ch = (Child) p; //This statement is not allowed. >>
If we run the program then we will get
An instance of the Parent class was created! An instance of the Parent class was created! An instance of the Child class was created! Exception in thread "main" java.lang.ClassCastException: co.java.exception.Parent cannot be cast to co.java.exception.Child at co.java.exception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:20)
Explanation:
In The Above Program, we are creating an instance of both the parent and child class. but when we are trying to assign the parent class instance to child class instance that will generate an exception.
Java – Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same exception or its parent classes. There is no problem if the parent class or child class constructor throws any unchecked exceptions. The child class constructor can throw any unchecked exception without looking for a parent class constructor.
Understanding behavior of constructor calls
Whenever a method that throws some exception is called by another method, then the calling method is responsible for handling that exception (The calling method is the method that contains the actual call; the called method is the method being called). In case of constructors, the parent class constructor is called by the child class constructor. It means the child class constructor is responsible for handling the exception thrown by the parent class constructor.
Now, for handling an exception there are two ways, one is to catch the exception and another is to throw it. But in the case of the constructor, we can’t handle it using the try-catch mechanism. The reason is that we enclose our code which can raise an exception in the try block and then catch it. The exception is raised due to a call to parent class constructor, like super(). It means if we want to handle the exception using try-catch is depicted in the below illustration.
Illustration 1
Child() < // Try- catch block try < super(); >catch (FileNotFoundException exc) < // Handling exception(code) >>
Actually, it is not correct as a call to super must be first statement in the child class constructor (refer super in java as it can be perceived from below illustration as follows:
Illustration 2
Child() < super(); // either called explicitly or added by the compiler in case of default constructor try < // your code >catch(FileNotFoundException exc) < // handling code; >>
and hence the exception can’t be caught (as its not inside the try block) and we can’t handle it using try-catch mechanism. That’s why we need to throw the exception. The below code will compile fine which will appear as follows:
// parent class constructor throws FileNotFoundException Child() throws FileNotFoundException < super(); // either called explicitly or added by the compiler in case of default constructor try < // your code >catch(FileNotFoundException exc) < // handling code; >>
Different Use-cases:
- Parent class constructor does not throw any checked exception
- Parent class constructor throws a checked exception
Now let us discuss each case in detail alongside justifying via clean java programs.
Case 1: Parent class constructor does not throw any checked exception
If the parent class constructor does not throw any exception then the child class can throw any exception or throw nothing.
Exception in Inheritance
a) Exception thrown in the parent class’s method is checked type.
If the exception is thrown by the parent’s class method then child class’s overridden method may not be required to throw the exception (not mandatory but it can throw)
class Parent < void method1() throws SQLException < >> class Child extends Parent < void method1() < >>
b) Exception thrown in the parent class’s method is unchecked type.
If the exception is thrown by the parent’s class method then child class’s overridden method may not be required to throw the exception(not mandatory but it can throw)
class Parent < void method1() throws RuntimeException < >> class Child extends Parent < void method1() < >>
Ground Rule :
If exception(checked/unchecked) is thrown in the parent class’s method then child class’s overridden method is not forced to through an exception. However it can through the exception if it wants(rules will apply).
Case 2 : Child class throwing checked exception
Child is throwing any checked exception but parent is not throwing any exception
class Parent < void method1() < >> class Child extends Parent < void method1() throws SQLException < >>
Will the above program executes successfully ?
It will fail at compile time.
The reason is, It’s throwing checked exception.
Ground Rule :
If the child class is throwing any checked exception then parent must also through same exception (OR) any of its parent exception otherwise compilation fails.
Case 3 : Child class throwing unchecked exception
class Parent < void method1() < >> class Child extends Parent < void method1() throws RuntimeException < >>
Compilation success ?
Yes , Because it is throwing run time exception
Ground Rule :
If the child is throwing any unchecked exception then parent need not to throw exception.
Let’s apply above Ground Rules for the below programs
1) Think and apply the Ground Rules
class Parent < void method1() throws SQLException < >> class Child extends Parent < void method1() throws RuntimeException < >>
Do you think above program compile successfully ?
Yes 🙂 Because Ground Rules are applied
1) If parent is throwing any exception then child may not be required to throw exception(but it can throw) satisfied 2) If the child is throwing any unchecked exception then parent need not to throw exception(but it can throw) satisfied
2) Now see the below program(just revrse of above program)
class Parent < void method1() throws RuntimeException < >> class Child extends Parent < void method1() throws SQLException < >>
Do you think above program compile successfully ?
Yes 🙂 it will compile
Think and apply the common Ground rules
1) If parent is throwing any exception then child may not be required to throw exception(but it can throw) Satisfied 2) If the child is throwing any unchecked exception then parent need not to throw exception(but it can throw) Satisfied 3) If child is throwing any checked exception then parent should throw same exception or its parent exception Not satisfied
So, Above program fails in compilation because child is throwing checked exception
3) Do you think below program compiles successfully ?
Creating Exception Classes
When faced with choosing the type of exception to throw, you can either use one written by someone else the Java platform provides a lot of exception classes you can use or you can write one of your own. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.
- Do you need an exception type that isn’t represented by those in the Java platform?
- Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
- Does your code throw more than one related exception?
- If you use someone else’s exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
An Example
Suppose you are writing a linked list class. The class supports the following methods, among others:
- objectAt(int n) Returns the object in the n th position in the list. Throws an exception if the argument is less than 0 or more than the number of objects currently in the list.
- firstObject() Returns the first object in the list. Throws an exception if the list contains no objects.
- indexOf(Object o) Searches the list for the specified Object and returns its position in the list. Throws an exception if the object passed into the method is not in the list.
The linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus, the linked list should provide its own set of exception classes.
The next figure illustrates one possible class hierarchy for the exceptions thrown by the linked list.
Example exception class hierarchy.
Choosing a Superclass
Any Exception subclass can be used as the parent class of LinkedListException . However, a quick perusal of those subclasses shows that they are inappropriate because they are either too specialized or completely unrelated to LinkedListException . Therefore, the parent class of LinkedListException should be Exception .
Most applets and applications you write will throw objects that are Exception s. Error s are normally used for serious, hard errors in the system, such as those that prevent the JVM from running.
Note: For readable code, it’s good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class.