Forums Register Login

ClassCastException

+Pie Number of slices to send: Send
Hi all,
Most of the time my code breaks it is due to some or other ClassCastException,any precautions i should take?
+Pie Number of slices to send: Send
ClassCastException generally creeps in when you try to cast an object of one type into another incompatible type. For e.g.

When you say String s = (String)(an object of StringBuffer);

The above will throw a ClassCastException.
But if an object is a type of the casted object, then it doesn't throw this exception.

e.g.
// this will not throw the exception
Object o = (Object)(any kind of object);

To avoid this kind of Exception, you may use the instanceOf operator to check whether your object is castable into a particular type.

Sid
[ May 16, 2007: Message edited by: Sidd Kulk ]
+Pie Number of slices to send: Send
Hi,
Thanks for your reply

Regards,
Srikkanth.M
+Pie Number of slices to send: Send
If U want to know what is the exact class of a given objet (ob),
ob.getClass() will tell U the class name
+Pie Number of slices to send: Send
Class casting is notoriously error-prone. Avoid it like the plague.

In Java 5 and more recent you use generics; you can specify what kind of object is allowed into a collection etc, and there is no need for class casts in the first place.
+Pie Number of slices to send: Send
Casting is for magicians, not programmers. Stop casting, and you'll stop getting exceptions from casts.
My name is Inigo Montoya, you killed my father, prepare to read a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 819 times.
Similar Threads
sorting a Vector
printing...static context?
Exceptions
Are girls dumber than guys ?
Final Class cannot be instantiated
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 02:08:30.