Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

throw and throws

 
Ravissant Markenday
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi everyone!

Could anyone please tell me the diffrence between the "throw" and "throws" clauses in exception handling?

thanks in advance,
Ravissant Markenday
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
throw - used when you want to throw exception explicitly. you can throw any exception which subclass of Throwable interface.

Example:

throws - used when you think that your method may throw exception, so caller should take care of it.

Example:
This method is from FileInputStream class. It says, if you use read() method then you need to catch IOException.
 
Ravissant Markenday
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Prabhu, so can both "throw" and "throws" be used for checked and unchecked exceptions???

Thanks again,

Warm Regards,
Ravissant Markenday
 
Ravissant Markenday
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes and one more question here, does jvm handle both checked and unchecked exceptions??

Thanks,

Regards,
Ravissant Markenday
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can both "throw" and "throws" be used for checked and unchecked exceptions???


Yes, you can.However, if throw unchecked exceptions using throw or throws, it is not mandatory for caller to handle it. means caller can call your method without try{}catch(){}.
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does jvm handle both checked and unchecked exceptions??


How JVM knows, how to handle the exception which occurred in your code?

JVM is the one who throws those exception, saying "Buddy, something wrong with your code, check it!".

hth,
 
Ravissant Markenday
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Prabhu !!!
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One small correction on the first reply to this question - Throwable is not an interface, but a perfectly instantiable class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic