Constructor exceptions

Here’s a real noodle scratcher when you first encounter it. This makes a good interview question since it forces candidates to talk through the construction sequence. This isn’t a question that I would necessarily expect someone to answer correctly but I would expect someone to be able to talk through the various cases and the effects of those cases.

* <p>Tests that refernces can be made to an member even though its constructor
* fails.</p>
public class ConstructorExceptionTest extends TestCase
* <p>Tests that refernces can be made to an member even though its
* constructor fails.</p>
public void testException()
final ArrayList<ConstructorException> objects = new ArrayList<ConstructorException>();
ConstructorException failedObject = null;
failedObject = new ConstructorException(objects);
} catch(final Exception e)
// ignore since it is required to occur
assertNull("The newly created member should be null.", failedObject);
assertTrue("The list should not be empty.", !objects.isEmpty());
final ConstructorException listObject = objects.get(0);
assertNotNull("References to the object still exist.", listObject);
assertNull("The object's member should be null.", listObject.member);
* <p>An member that throws an exception on construction to ascertain what
* ooccurs to references to it that are made before the construction
* completes.</p>
private class ConstructorException
* <p>Some member that is "created" after the constructor should have
* failed.</p>
final Object member;
* <p>Adds itself to the specified list of objects before it throws an
* exception.</p>
* @param  objects a list of objects to which this member adds itself
* @throws Exception always
public ConstructorException(final List<ConstructorException> objects)
throws Exception
throw new Exception();
/* else -- cannot occur */
member = new Object();

I should point out to all of you doubting Thomas’ out there that this test runs green. I should also point out that the if(true) is a trivial replacement for anything that can go wrong during construction.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s