Exception handling in constructors

Is exception handling in constructors an accepted coding practice?

Page 1 of 1

3 Replies - 10770 Views - Last Post: 29 July 2008 - 09:15 AM Rate Topic: -----

#1 animal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 28-July 08

Exception handling in constructors

Post icon  Posted 28 July 2008 - 12:27 PM

Is exception handling in constructors an accepted coding practice?

If yes, is there anything to be aware of?
Is This A Good Question/Topic? 0
  • +

Replies To: Exception handling in constructors

#2 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: Exception handling in constructors

Posted 28 July 2008 - 01:07 PM

Most companies have a Developers Document that should answer this for you, but normally no, the constructor should be used for Initialization of objects with in that class, and methods are used to do something with those objects, so in your methods you do exception handling.
Was This Post Helpful? 0
  • +
  • -

#3 kikz  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 32
  • Joined: 21-July 08

Re: Exception handling in constructors

Posted 28 July 2008 - 02:41 PM

The problem with putting excepting handling in your constructor is, as said above, your constructor initialises the state of the object. If initialisation is incorrect and you silently continue, by way of handling any exceptions inside the constructor, your object could be in an invalid state. If you are going to catch exceptions inside the constructor, just catch, perform any sensible handling, and rethrow.
Was This Post Helpful? 0
  • +
  • -

#7 KyleG  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 44
  • Joined: 11-June 08

Re: Exception handling in constructors

Posted 29 July 2008 - 09:15 AM

Yes, you should always handle all possible exceptions in your constructor. Ideally, you should write classes that don't have complex constructors capable of causing exceptions. But the bottom line is this: Your constructor should never throw an exception to the code that's creating an instance of your class. Secondary to that goal: It should not be possible to create an instance of your class in an invalid or partially initialized state. If handling all exceptions in your constructor makes it possible to create an instance that's invalid/unusable, you should rewrite your class. If you can't rewrite your class (which you should really really do), at least then it will be your class methods that throw exceptions rather than the constructor. From my experience, it's much more likely that the "client" code that uses the instance's methods will be within a try/catch block than the code that creates the instance.
Was This Post Helpful? 1

Page 1 of 1