Is exception handling in constructors an accepted coding practice?
If yes, is there anything to be aware of?
Exception handling in constructorsIs exception handling in constructors an accepted coding practice?
Page 1 of 1
3 Replies - 9323 Views - Last Post: 29 July 2008 - 09:15 AM
Replies To: Exception handling in constructors
#2
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.
#3
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.
#7
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.
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|