2

Possible Duplicate:
Throwing exceptions from constructors

When initializing an object - what would be the correct way to handle an issues that will prevent the object from fulfilling all of its responsibilities later on down the line.

For example, say a constructor initializes a set of config variables that are used for a remote connection. Not all config variables have been properly set and so later, when the object is used for that connection it will simply not work and ultimately throw an exception.

I can think of a couple of solutions to this

  1. The constructor throw an exception there and then
  2. The object provides a method for validating the config settings (this means clients of that object have the added task of checking valid state before using)
  3. Simply leave as is and let any exceptions be thrown, leaving clients to deal with them if they arise.

So, which of these options would be considered the best approach in the scenario provided, or if there is an alternative better way of handling this, what would that be.

Community
  • 1
  • 1
Marty Wallace
  • 34,046
  • 53
  • 137
  • 200
  • depends on the langage and how you pass the config variables. your set of variables may be an instance of a class, like an adapter and let the adapter validate the config variables and throw something , not the initializer itself. – mpm May 19 '12 at 21:15

1 Answers1

1

Definitely throw an exception. It abstracts your handling so much.

It allows you to handle it in any way you want, including (but not limited to):

  • Set a variable to determine which features were enabled in your object and which were not.
  • Call a method on said object.
  • Display an error to the user
  • Invoke some sort of error logging

If not handled, Exceptions would kill the script, giving you a detailed debug backtrace of what went wrong.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • so you suggest throwing an exception from within the constructor should a config value not being set properly that will be required later for the object to function fully? – Marty Wallace May 19 '12 at 21:18
  • 1
    Definitely throw an exception /as soon as you know something is wrong/, which is most likely in your constructor. – Cory Carson May 19 '12 at 21:18
  • @user1189880: Exceptions should be thrown in exceptional cases. Exceptional cases are cases where not everything has gone according to plan. (You expected the database to connect, but something was wrong and it failed. You throw an exception). It's very likely that if things didn't go according to plan, it would affect the abilities of the object later on. – Madara's Ghost May 19 '12 at 21:19