Activity 4.6 - Writing a user-defined exception class
Topic
Here we extend the previous
activity to employ a user-defined exception class.
Materials
In addition to the Solution
document, the project for this activity contains three classes:
-
Read_a_Sonnet, which you will need to modify;
-
FileFormatException, which is incomplete;
-
Main, which contains test code for the
activity.
In addition, there is a
text file, sonnet1.txt, 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 the first fourteen lines
of the file sonnet1.txt and will print them out one by one. The main method should handle any exceptions
of type IOException that may occur.
Instructions
-
Run
the project and check that it displays the fourteen-line poem correctly.
-
Open the class FileFormatException, and complete the definition of this
user-defined exception class.
-
In class Read_a_Sonnet, make appropriate changes so that the relevant methods throw and handle
a FileFormatException, rather than an EOFException, if the file does not have enough
lines.
-
Check that your modified classes work both for a file with at least the required
number of lines (14) and for a shorter file (edit the text file in the IDE).