PHP Exceptions – Should You Throw Exceptions from a Constructor?

exception handlingexceptionsobject-orientedPHP

I know I can throw exception from constructor in PHP but should I do it? For example, if a parameter's value is not as I expected it.

Or should I defer throwing an exception till a method is invoked. What are advantages and disadvantages in both cases?

Best Answer

Why would you postpone throwing the exception?

If you know that the object can't properly instantiate with the given parameters, then you should definitely throw an exception.

Otherwise, somebody might test your object for null, which it won't be, and could assume everything went as expected.

There are a lot of things that can be done to your object without calling a method on it: it could be added to a list, it could be compared, it could be sent as a parameter, etc etc etc. All of these are things that should not have happened, considering it is not a valid object.