Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

There are two sensible options that a constructor or factory method could use to

ID: 3888903 • Letter: T

Question

There are two sensible options that a constructor or factory method could use to report failure. It could throw an exception, or in the case of a factory method, it could return null. Look at the code distributed with the Sept. 14 lecture notes, in the readNetwork method. This code contains the line:

What we want, with either solution, is to not-only not create a new intersection, but not add anything to the list inters.

a) Rewrite this line so that it handles the Intersection.ConstructorFailure exception thrown by the constructor.

b) Rewrite this line so that it handles a return value of null from a call to a factory method that replaces new Intersection().

static void readNetwork( Scarner sc) while (sc. hasWext)) i // until the input file is finished String command = sc. next(); if ("intersection". equals command)) inters. add new Intersection sc, inters roads. add new Road( sc, inters) ): // Bug: Should probably support comments telse 11 road. equals comun and) l else l Errors.warning + command + ”, not a road or intersection. // Bug: Should skip to the next line

Explanation / Answer

a) When constructor has facility to throw the exception. we would say:

try {

var intersection = new Intersection(sc);

}

catch (exception ex) // catch specific exception in case you have defined custom exception or thrown specific ex.

{

//log exception details

logger.write(""Exception in creating Intersection object. " + ex.Message);

}

(in case you don't want to handle exception here and you want to handle it at the parent calling funciton then don't change anything,

b) When factory method with null return value:

var intersection = InterSectionFactory.GenerateInterSeciton("sc");

if (intersection != null) {

// log a message or throw an exception as per requirements.

throw new InterSectionCreationException("Message");

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote