[nycphp-talk] PHP 5 Throwing Exceptions in Constructors
Ophir Prusak
prusak at gmail.com
Wed Feb 9 21:33:39 EST 2005
Hi Hans,
I was dealing with this exact same dilemma on a project I'm currently coding.
We ending up going with Adam's option B: move the code which can fail
to outside the constructor.
In the original design the you could create an object where the
constructor could read some information from a database.
In the final design, we moved the database code to a new load()
function that executes the actual database call. This does add an
additional step, but having the constructor throw an execution just
messes things up.
Ophir
On Wed, 9 Feb 2005 15:01:31 -0500, Hans Zaunere <lists at zaunere.com> wrote:
>
> Hi all,
>
> All PHP 5 code examples I've seen show try/catch pairs like this:
>
> try {
> $obj = new MyClass;
> $obj->DoSomething();
> } catch( Exception $e ) {
> echo $e->getMessage();
> }
>
> I am the only one in thinking that these examples are incorrect 99% of the time? Based on other languages, like Java, exceptions should very very rarely be thrown from a class' constructor. The simple reason, as in PHP 5, is that the object never gets created if an exception is thrown in the constructor.
>
> Is there something particular to PHP 5 that I'm missing? While it could be considered pedantic, PHP 5 code examples should be as:
>
> $obj = new MyClass;
>
> try {
> $obj->DoSomething();
> } catch( Exception $e ) {
> echo $e->getMessage();
> }
>
> In fact, in PHP 5 I cannot find anyway to determine the "return" value of the new operator. This leads me to believe that PHP 5's concept of proper OO is to always assume the object is created successfully, unless a catastrophic event happens, in which case an exception is thrown, and the object isn't created at all. This of course makes sense, but then I'm confused as to why the code samples all seem a bit incorrect.
>
> Interested in hearing thoughts on this...
>
> ---
> Hans Zaunere
> President, Founder
> New York PHP
> http://www.nyphp.org
>
> _______________________________________________
> New York PHP Talk
> Supporting AMP Technology (Apache/MySQL/PHP)
> http://lists.nyphp.org/mailman/listinfo/talk
> http://www.nyphp.org
>
More information about the talk
mailing list