Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with wrapping a method in try/catch block  RSS feed

 
Rohan Deshmkh
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



If i replace YYY s =new YYY();
with
XXX s =new YYY();
then why is it necessary to wrap the main method in try/catch block . The s.m() will call the method m from class YYY, which does not throw any exception.So it shouldn't be necessary to wrap it in a try/catch block.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler only knows and cares about the reference type (which is fixed at compile time), not the object class (which can be determined at runtime).

That is, it only cares about XXX s, not about =new YYY(), and since XXX.m() is declared to throw Exception, you have to deal with it.

So, yes, is should be (and is) necessary to catch or declare Exception. Whenever the compiler or the runtime does X, and you find your self thinking, "It should be doing the opposite of X," it's time to reevaluate your assumptions.
 
Rohan Deshmkh
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK thanks, got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!