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

Answer:

A try must be followed by:


No catch

import java.util.*;
import java.io.*;

public class SumFileData 
{
  public static void main (String[] args) throws IOException 
  { 
    int num,sum = 0;
    Scanner scan = null, scanUser = null;
    String fileName;
    
    try 
    {
      scanUser = new Scanner( System.in );
      System.out.println("Input file name: ");
      fileName = scanUser.nextLine().trim();
      
      File file = new File( fileName ); // create a File object
      scan = new Scanner( file );      // connect a Scanner to the file

      while( scan.hasNext() )   // is there more data to process? 
      {
        num = scan.nextInt();
        sum += num;      
      }
      
      System.out.println("Sum = " + sum );
    }
    
    finally 
    {
      if ( scan != null ) scan.close();
    }
  }
}

The try block of this program might generate several types of Exceptions, but they are not handled.

However, good programming practice calls for closing a file if it has been opened. The finally block will always execute, no matter what has happened in the try block. So the file connected to scan will always be closed.

It is not necessary to close System.in because that is controlled by the runtime system.


QUESTION 6:

Is it necessary to declare throws IOException in the method header?


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