New! Should A Constructor Throw An Excep ...

New! Should A Constructor Throw An Exception?

Feb 19, 2024

Let's say you had a class that you wanted to use, but there was some sort of error in creating the object. This might be that the wrong parameters were passed, or the third party service (eg. a database) wasn't available at the time of creation.

If this happens you'll obviously want to handle the error correctly, but the question is would you throw an exception in the constructor or handle the error condition elsewhere?

Note that this article will talk about PHP, but the same discussion applies to other languages that implement OOP principles.

I did some reading on this subject and it appears that there's roughly two camps of thought with regards to this, these are:

  • If there was a problem the object should exist, but shouldn't be usable.

  • If there was a problem the object shouldn't exist if it is not usable.

Read more here:

Enjoy this post?

Buy !# code (Hash Bang Code) a coffee

More from !# code (Hash Bang Code)