0
Imcompatible Types :Compile Time And ClassCastException:Run time
can someone please explain the difference and in depth with examples and also does all the exceptions occur at run time though we check them
2 Respuestas
+ 2
Exceptions occur at run time and compile time also.
Complile time Exception are called Checked exception. Programmer must take care of this.
Runtime Exceptions are called unchecked exception. You can't handled this by program..
ClassCadtException occurs when you try to cast incompatible class objects.. For example float to string casting is possible but when you try to cast string to float, it raise incompatible class cast exception in this
(Float)"string" ; //wrong like Float f = new Float("str");error.
12.5 cast to string is possible i mean by by String s = new String("12.5");
Another example, When you try to cast a class Refference to another class Refference which don't have any relation like inheritance, then it raise ClassCadtException.
Its a wide topic, you can go through this link,. And post if for anything not understandable.. I try my best if i know..
https://www.javamadesoeasy.com/2015/05/checked-compile-time-exceptions-and.html?m=1
https://www.javatpoint.com/exception-handling-in-java
+ 1
You can catch everything, but catch unchecked is not mandatory and also it's not a good idea.
//String s = (String)(12.5); //this is not possible, (error: incompatible types)
int i = (int)(12.5); //ok
ClassCastException
"attempted to cast an object to a subclass of which it is not an instance."
Object x = 100;
String s = (String) x; //ClassCastException