Discussion of Activity 4.6 - Writing a user-defined exception class

Here is our sample solution for the FileFormatException class:

public class FileFormatException extends Exception
{
   // add a zero-argument constructor here
   public FileFormatException()
   {
      // implicitly invokes the superclass zero-argument
      // constructor
   }
   // add a one-argument constructor here
   public FileFormatException(String message)
   {
      // invoke the superclass one-argument constructor
      super(message);
   }
}

All the work is done by the superclass in this case.  More complex exception classes may have their own instance variables and methods. 

Our sample solution for the modified class Read_a_Sonnet follows. We simply replace EOFException by FileFormatException throughout the class:

import java.io.*;
public class Read_a_Sonnet
{
   private FileReader fr;
   private BufferedReader br;
   final static int LINES_IN_SONNET = 14;

   public void run() throws IOException
   {
      openFile("sonnet1.txt");
      try
      {
         readLines(LINES_IN_SONNET);
      }
      catch (FileFormatException ex)
      {
         System.out.println("Wrong number of lines in poem. " + ex);
      }
      finally
      {
         closeFile();
      }
   }

   // open the specified file
   private void openFile(String fileName) throws IOException
   {
      fr = new FileReader(fileName);
      br = new BufferedReader(fr);
      System.out.println("== File "+ fileName + " opened OK"); // just for testing
   }

   // read and display the specified number of lines from text file
   // Note: we do need to list FileFormatException separately.
   private void readLines(int numberOfLines)
   throws IOException, FileFormatException
   {
      String nextLine;
      int lineCount;
      nextLine = br.readLine();
      lineCount = 0;
      while (nextLine != null && lineCount < numberOfLines)
      {
         lineCount++;
         System.out.println(nextLine);
         nextLine = br.readLine();
      }
      if (lineCount < numberOfLines)
      {
         throw new FileFormatException("read " + lineCount + " lines");
      }
   }
   // close the text file
   private void closeFile() throws IOException
   {
      br.close();
      fr.close();
      System.out.println("== File closed OK"); // just for testing
   }
}

Notes

Note that method readLines has been declared as throwing both IOException and FileFormatException. Unlike in the previous activity, where we used EOFException , it is necessary to declare both exceptions since FileFormatException is not a subclass of IOException.

Try removing FileFormatException from the declaration, if you want to confirm this.