50

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?

user
  • 2,210

5 Answers5

82

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.

Andrei G
  • 1,127
22

If your constructor is invoked with bad parameter(s) then you should (must?) throw an exception. If you do not then you could get a bad object which will not behave as expected.

20

Absolutely!!

You should throw the exception if the parameters for constructing the object is not valid or not as per the contract. It is not a good idea to go ahead with the flow knowing that the object is constructed with bad data which can cause many issues if you allow the caller to go ahead.

It is always better to "FAIL FAST AND FAIL EARLY"

java_mouse
  • 2,657
  • 17
  • 23
8

I know I can throw exception from constructor in PHP but should I do it?

That is the only sane way to inform that the object construction failed.

BЈовић
  • 14,049
4

Why would you not validate the parameter set prior to instantiating your object? Doing so would ensure that your object would be created, thus, removing any of the side affects that may occur from its failure.

Though I know you can check things in your constructor and toss exceptions, I prefer to write my constructors in such a way that they do not fail. I perform parameter validation before instantiating objects which I can then toss exceptions without having my constructors fail. I also generally do not try to instantiate new objects in my constructors, choosing instead to instantiate them as I need them.

Just my opinion. PHP offers a lot of freedom - enjoy!