go to previous page   go to home page   go to next page

Answer:

An EOFException is thrown when the end of a file is reached.


Reading until EOF

public static void main()
{
  . . .
   
  try
  {
    while ( true )
      sum += instr.readInt();
  }
  
  catch ( EOFException  eof )
  {
    System.out.println( "The sum is: " + sum );
    instr.close();
  }

  . . .
    
}

Most methods of DataInputStream throw an EOFException when the end of a file is reached. Let us work on a program (above) that uses this idea to read 32-bit integers until end of file.

The while loop keeps going until readInt() hits the end of the file. Then an exception is thrown and execution jumps out of the loop to the catch{} block.


QUESTION 9:

Will catch ( EOFException eof ) catch an IOException that is not an EOFException?