Help: Creating and Throwing Exceptions


Help is available for each task, or you can go straight to the solution source code.

Task 1

Fill out the method buildEngine to throw the proper exception if the engine build is bad.
The exception to throw is EngineException. Add a throws clause to the method declaration. In the body of the message, throw a new instance of this exception if the enginesGood variable is false.

Task 2

Repeat the above for the methods buildFrame and assembleComponents.
As in the first task. The exceptions to throw are FrameException and ComponentException. Add the throws clauses to the method declarations. Then in the bodies of the messages, throw the proper exceptions if the construction area is not good.

Task 3

Fill out the method buildComponents. Each exception that can be thrown by the methods calls in buildComponents should be caught individually, an error message printed to System.out, and a new ComponentException thrown.
Since the method buildComponents may throw ComponentException, add a throws clause to the method declaration. Wrap the existing body of the method in a try block. Add two catch blocks, one for EngineException, the other for FrameException. For the handler code of each catch, print a message to System.out and throw a new instance of ComponentException.

Task 4

Fill out the build Airplane method. It should catch the appropriate exceptions and print errors to System.out.
Wrap the existing body of the method in a try block. Two exceptions need to be caught, ComponentException and AssemblyException. The handler code for each catch should print a message to System.out.

Task 5

The main method creates some new factories and excercises them. Compile and run the application. Examine the output for correct behavior.
Each test should throw one of the exceptions: engines, then frames, then assembly, then everything. The last case should result in the same output as the first, since engines are built first, and construction fails if engine building throws an exception.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.