Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException

 
Srikkanth Mohanasundaram
Ranch Hand
Posts: 243
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Most of the time my code breaks it is due to some or other ClassCastException,any precautions i should take?
 
Sidd Kulk
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Srikkanth Mohanasundaram
Ranch Hand
Posts: 243
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for your reply

Regards,
Srikkanth.M
 
jayalal jayarathna
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If U want to know what is the exact class of a given objet (ob),
ob.getClass() will tell U the class name
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting is for magicians, not programmers. Stop casting, and you'll stop getting exceptions from casts.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic