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

Casting Throwbale to Exception

 
Surendra Kumar
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As we all know casting super class onject references to subclass references gives ClassCastException.

But casting Throwbale to Exception doesn't give any exception.

why so? is it exception?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you explain what you tried?

I tried this simple program, and it gives a ClassCastException.


[ August 23, 2006: Message edited by: Keith Lynn ]
 
Surendra Kumar
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you add a print statement in the catch block to see the type of exception it is, you will see that it is a ClassCastException.

So the attempt to cast the Throwable object to an Exception causes the ClassCastException. Since ClassCastException is a subclass of Exception, the catch block will catch it.
[ August 23, 2006: Message edited by: Keith Lynn ]
 
Surendra Kumar
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you're right.
Thanks a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic