NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP 5 Throwing Exceptions in Constructors

Matthew Terenzio matt at jobsforge.com
Thu Feb 10 18:55:24 EST 2005


On Feb 10, 2005, at 12:20 AM, Adam Maccabee Trachtenberg wrote:

>
>>> Is it possible to gain some insulation in certain cases by using a
>>> specific exception subclass object type?
>>
>> To clarify what I mean, I'm wondering if Hans can't add an additional
>> catch like Example 20-3->example 1 below
>> and somehow only abort the instantiation if a critical exception is
>> thrown
>
> It up to you to choose if you want to abort the
> instantiation. However, if you want to return an error in a
> constructor, you need to throw some form of exception. It can either
> be the base Exception class, or a subclass, but you can't do something
> like returning false.

Yeah, but some generic exception thrown from a class two or three 
levels away shouldn't be a concern of a developer who may not even be 
aware of the inner workings of that class.
Back at the example below,  I do believe  something like the Java 
compiler would complain about  new Child in the Top class because the 
child constructor can throw a bad value exception, therefore it must be 
caught.
That would make the subsequent user of the Top class shielded , no? 
That is, the exception would be caught before it got into the arms of 
the try/catch below.
But with no enforcement, I guess it's kinda hairy.
Correct me if I'm wrong. I'm learning this, not arguing it.

class Top
{
	protected $Child;

	public function __construct( $value ) {
		$this->Child = new Child($value);
	}
}

class Child
{
	public function __construct( $value ) {
		throw new Exception('Bad Value');
	}
}

try {
	$mytop = new Top($_POST);
} catch( Exception $e ) {
	echo 'You had an exception';
}





More information about the talk mailing list