This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors

 
Nagendra Prasad
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
Hopefully a basic question this.. are constructors allowed to catch/throw exceptions?
Regards,
prasad.
 
Grishma Dube
Ranch Hand
Posts: 275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have a constructor which throws exception using 'throws' keyword, which shows the constructor is capable of raising the exception but the exception must be handled by the calling method.
It means in your main method create object of the class inside try and catch the exception in catch block correspondint to it.
Hope you got my point.
 
Nagendra Prasad
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response... Got your point... no problems with that.. and the logic u have described is how I have actually implemented it.. but I what I was wondering was is it a good practice ( best practice... philosophically correct.. whatever..) to have constructors throwing exceptions?
Regards,
Prasad.
 
Grishma Dube
Ranch Hand
Posts: 275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends. But in most of the cases, it makes a perfect sense. Especially when the constrctor is taking intial size as a Parameter, it that size is negative then immediately it will throw an exception.
In a way, its a good practice.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic