Activity 4.5 - Developing a class that throws exceptions
Topic
This activity extends a
previous exercise on reading from a text file to include throwing and catching
exceptions.
Materials
In addition to the Solution
document, the project for this activity contains two classes
-
Read_a_Sonnet, which is incomplete;
-
Main, which contains test code for the
exercise.
In addition, there is a
text file sonnet1.txt that is not part of the project but which can be found in the project
folder. This contains a well-known sonnet (a fourteen-line poem) by William
Shakespeare.
Task
The run method of the class Read_a_Sonnet will read successive lines of the file sonnet1.txt and print them out one by one,
halting when it meets the end of the file. The main method should handle any exceptions
of type IOException which may occur.
Instructions
Run the project and check
that it displays the full contents of the text file.
- Open the class Read_a_Sonnet, change the name of the text file
from sonnet1.txt to the name of a non-existent file such as sonnet2.txt and run the project again. This
should cause an exception, which will be caught and reported by the main method. Note how the exception was
propagated from the method where it was thrown to the first appropriate handler
(in the main method).
- In class Read_a_Sonnet, change the text file name back to sonnet1.txt. Then make the other changes
indicated within the source file, so as to read exactly the correct number of
lines and to throw an EOFException if the text file does not contain
enough lines. This exception should be caught and reported in the run method. Check that this works both
for a file with at least the required number of lines (14) and for a shorter
file. You can use File|Open File... to open and edit the file in the IDE. When you
delete lines, make sure the lines themselves have actually been deleted, not
just their contents. You can check this by pressing the down arrow key on the
keyboard. If the cursor moves below the last line of visible text one or more
blank lines still need to be removed.
- When you are satisfied that this works correctly, modify the run method of the class Read_a_Sonnet, to include a finally clause. This should ensure that the
file is always closed after use, even if an exception occurs while reading the
file. Check that this works by running the project first on a valid file and
then on a file which will give rise to an EOFException.