• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

ClassCastException

 
Ranch Hand
Posts: 243
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Thanks for your reply

Regards,
Srikkanth.M
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 80874
506
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Casting is for magicians, not programmers. Stop casting, and you'll stop getting exceptions from casts.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic