How to Solve Class Cast Exceptions in Java?
Last Updated :
02 Jun, 2023
An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.
Examples of checked exceptions are classNotFoundException, IOException, SQLException etc.
2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception.
Examples of unchecked exceptions are ArithmeticException, ArrayStoreException etc.
Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
ClassCastException: It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM whenever we try to improperly typecast a class from one type to another i.e when we're trying to typecast parent object to child type or when we try to typecast an object to a subclass of which it is not an instance.
In the below program we create an object o of type Object and typecasting that object o to a String object s. As we know that Object class is the parent class of all classes in java and as we're trying to typecast a parent object to its child type then ultimately we get java.lang.ClassCastException
Java
// import required packages
import java.io.*;
import java.lang.*;
import java.util.*;
// driver class
class geeks {
// main method
public static void main(String[] args)
{
try {
// creating an object
Object o = new Object();
// type casting the object o to string which
// give the classcasted exception because we
// type cast an parent type to its child type.
String s = (String)o;
System.out.println(s);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Outputjava.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')
In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type. While using Collections we can prevent ClassCastException by using generics because generics provide the compile-time checking.
Below is the implementation of the problem statement:
Java
// import required packages
import java.io.*;
import java.lang.*;
import java.util.*;
// driver class
class geeks {
// main method
public static void main(String[] args)
{
try {
// creating an object
String s = "GFG";
Object o = (Object)s;
// Object class is parent class of every class
// Hence exception doesn't occur.
System.out.println(o);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Similar Reads
How to Solve java.lang.ClassNotFoundException in Java? In Java, java.lang.ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. ClassNotFoundException should be handled with a try-catch block or using the throw keyword. In ol
4 min read
How to Fix java.lang.classcastexception in Java? ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class. Here we can consider parent c
6 min read
How to Solve ConcurrentModificationException in Java? An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote fil
4 min read
Class cast() method in Java with Examples The cast() method of java.lang.Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Syntax: public T[] cast(Object obj) Parameter: This method accepts a parameter obj which is the object to be cast upon Re
2 min read
Method Class | getExceptionTypes() Method in Java The java.lang.reflect.Method.getExceptionTypes() method of "Method class" returns an array of Exception Type Class Objects declared to be thrown by the method object to handle exception inside the method. All the exceptions handled by method using thrown clause, are returned as array of Class object
3 min read
Best Practices to Handle Exceptions in Java Exception Handling is a critical aspect of Java programming, and following best practices for exception handling becomes even more important at the industry level, where software is expected to be highly reliable, maintainable, and scalable. In this article, we will discuss some of the best practice
7 min read
Errors V/s Exceptions In Java In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program. Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system cr
5 min read
Top 5 Exceptions in Java with Examples An unexpected unwanted event that disturbs the program's normal execution after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the expected termination of the program. Illustration: Considering a real-life exa
5 min read
Types of Exception in Java with Examples Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situati
8 min read
Built-in Exceptions in Java with examples Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. Examples of Built-in Exception:1. Arithmetic exception : It is throw
8 min read