Java lang classcastexception что это
Перейти к содержимому

Java lang classcastexception что это

How to Solve Class Cast Exceptions in Java?

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.

6 Java исключений, которые преследуют новичков

NoClassDefFoundError : Это одно из тех исключений, которое сообщением Exception in thread “main“ NoClassDefFoundError часто приветствует новых разработчиков в мире Java программирования. Они пишут helloworld-программу, идут в командную строку и пишут “java“ — команду для выполнения и «БАМ»:-) Немного времени спустя новички поймут как исправить это исключение и увидят как выводиться их hello world.

NoClassDefFoundError случается тогда, когда виртуальная машина Java (JVM) пытается получить доступ к классу во время исполнения и этот класс не находится, хотя тот же класс находился во время компиляции. Чаще всего это исключение случается при запуске Java программы через команду “java“ с неверным значением параметра classpath . [ Classpath – это параметр, который задается через командную строку или через переменную окружения, указывающий виртуальной Java машине или Java компилятору где искать классы или пакеты объявленные пользователем – прим. переводчика] Возможные причины исключения:

  • Класс недоступен в Classpath .
  • Часто скрипт, который исполняется при запуске операционной системы, изменяет значение переменной окружению classpath . Это можно проверить выполнив команду “ set ” в командной строке в Windows и посмотрев включено ли определение класса в значение classpath . При желании дальнейшее изучение этого исключения можно продолжить в блоге Javarevisited.

ClassNotFoundException : Исключение ClassNotFoundException это еще одно исключение, из-за которого новичкам, только начинающим программировать на Java, снятся кошмары. Интересно что для среднего разработчика нужно некоторое время чтобы перестать путать ClassNotFoundException и NoClassDefFoundError между собой. И поэтому вопрос о разнице этих двух исключений остается одним из часто задаваемых на собеседовании на позицию junior Java разработчика.
ClassNotFoundException случается когда JVM пытается загрузить определенный класс и не обнаруживает такого же в classpath . Обычно новички сталкиваются с этим в коде, который подключается к базе данных используя JDBC библиотеку. Пытаясь загрузить драйвер с помощью следующего кода Class.forName( “JDBCdriver”) . Хороший материал по ClassNotFoundException можно найти здесь. Так же рекомендуется ознакомиться и понять концепцию загрузчиков классов в Java чтобы эффективно справляться с этим исключением. Вы возможно захотите посмотреть следующую страницу о том как настроить classpath в окружениях Win/Unix. А так, как следует из документации Java, это исключение случается в следующих случаях:

  1. Когда пытаются загрузить класс используя метод Class.forName и файл .class не существует в classpath . Это самый частый случай из всех трех.
  2. Когда загрузчик класса пытается загрузить класс используя метод loadClass .
  3. Когда загрузчик класса пытается загрузить класс используя findSystemClass .

NullPointerException : исключение NullPointerException понять легче и новички с ним справляются быстрее нежели с двумя предыдущими. В тоже время причину исключения очень легко найти так как приводится номер строки где оно случилось. В первую очередь исключение случается когда JVM пытается обратиться к null в том месте где должен был быть объект. Чаще всего это случается когда JVM пытается вызвать метод используя объект и оказывается что объект равен null . Другие случаи, как упоминается в документации Java, могут быть следующими:

  1. Получая доступ к или изменяя метод объекта, который равен null .
  2. Получая длину массива когда он равен null .
  3. Получая доступ к или меняя объекты, которые являются заключенными в массив, который равен null .

IllegalArgumentException : Это исключение самое простое, его легко понять, найти его причину и исправить. Оно случается когда JVM пытается передать методу неподходящий аргумент или аргумент неправильного типа.

Handling the ClassCastException Runtime Exception in Java

Handling the ClassCastException Runtime Exception in Java

Runtime exceptions are exceptions which can not be checked at compile time. In Java, there are a myriad of classes derived from the RuntimeException class [1], all of which represent unchecked exceptions that need to be carefully considered and managed. Despite being less serious and critical than the unchecked runtime errors [2], these exceptions can still be very problematic and cause unexpected issues at runtime, especially if necessary precautions aren’t taken and relevant exception handling mechanisms aren’t put in place.

What is ClassCastException and When does it Happen?

As its name implies, ClassCastException is an exception that happens when the JVM tries to cast an object to a class (or in some instances, an interface) and fails. This relates to explicit type casting [3] and the reason the cast fails can be traced to an attempt at downcasting an object to a class of which it is not an instance, or to an interface which it does not implement.

ClassCastException is a subclass of the RuntimeException class which means it is an unchecked, runtime exception [4]. This exception can not be checked at compile-time because the compiler has no way of knowing whether the object is actually an instance of the target subclass, or if it is an instance of a subclass that implements the target interface. Consequently, if either of these scenarios is encountered at runtime, Java will throw the ClassCastException exception.

The only scenario where the compiler is able to detect invalid type casts of this kind is when the source type is a final class and it neither extends nor implements the target type, because it is known in advance that the final class does not have any subtypes, i.e., it cannot be subclassed [5].

How to handle ClassCastException

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type. To help achieve type safety and catch these issues at compile time, two builtin Java mechanisms are available:

  1. the instanceof operator, and
  2. Generics.

ClassCastException Examples

To better understand ClassCastException , consider the following Java class hierarchy:

The resulting scenarios can be summarized as follows:

  • It is possible to cast an instance of X , Y , or Z , to Object , since all Java classes implicitly inherit the java.lang.Object class [6].
  • It is possible to cast an instance of Y or Z to X , because they are both subtypes of X .
  • It is possible to cast an instance of type X to type Y (or Z ) ONLY if the original object is of type Y (or Z ), due to polymorphism [7].
  • It is impossible to cast an instance of Y to Z despite the fact that they are both derived from X , because Y and Z are unique types with distinct states and behaviors.

Complete examples and ways to deal with ClassCastException are presented below.

Using the instanceof operator

Java’s instanceof operator is a binary operator used to test whether the object is an instance of a specific class, or a class that implements a specific interface [8]. When used in the appropriate context, this operator can prevent the ClassCastException exception from occurring. The code example below shows how trying to cast an instance of Phone to a subclass of Phone ( Smartphone ) throws the ClassCastException exception.

Casting an object to an interface is also a valid polymorphic operation, so one might try to cast the myPhone variable to a Wireless instance instead. However, since myPhone is not an instance of any class that implements Wireless , the ClassCastException is thrown again.

The solution here is to use the instanceOf operator which will enforce a safe type cast, as shown below.

The same concept applies to interfaces:

Since myPhone is neither an instance of Smartphone nor an instance of a class that implements Wireless , the instanceOf operator inside the if statement evaluates to false, and the corresponding else clause is executed.

On the other hand, if an object passes the instanceOf check, then it can be safely cast to the specified type. This can be observed in the example below where the myPhone variable is an actual instance of the Smartphone class (as initialized on line 16).

As a side note, older versions of Java which don’t support pattern matching for the instanceOf operator [9] will require an extra step to cast the object manually, as follows:

Using Generics & Parameterized Types

Introduced in Java 5, Generics are a very important addition to Java’s type system which brought compile-time type safety and eliminated the need for the tedious type casting when working with the Collections Framework [10]. This mechanism allows programmers to implement generic data structures and algorithms that are type-safe, and it allows Java compilers to perform strong type checking and detect related issues at compile-time.

A parameterized type is an instantiation of a generic type with an actual type argument. The code below shows how the use of raw, unparameterized collections such as List s can easily lead to the ClassCastException being triggered. This is because unparameterized collections default to the Object type, so nothing prevents a program or an API from inserting an instance of an unexpected type into a collection. The example below shows how inserting and later trying to cast the string “200” into a List instance throws the ClassCastException exception.

Using Generics to make the List parameterized restricts the types of objects the list can hold to valid instances of Integer , which in turn makes any attempt to insert any other, incompatible type in the list detectable at compile-time, as shown in the revised example below.

Furthermore, using parameterized types to instantiate Generics eliminates the need to cast collection objects manually, so a working version of the example above could look something like this:

Conclusion

Runtime exceptions are an inevitable evil that all Java programmers have to face at some point. One of these exceptions is the ClassCastException which is thrown whenever there is an attempt to cast an object to a class or an interface the object is incompatible with. As with other runtime exceptions, being prudent is important and pays off in the long run. This article explains what causes the ClassCastException by diving into Java’s type casting rules, and it shows how to prevent and effectively deal with this exception by relying on the instanceof operator and using generic, parameterized types when the situation calls for it.

Track, Analyze and Manage Errors With Rollbar

Managing Java errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *