A try
must be followed by:
catch
blockscatch
blocks and a finally
blockfinally
blockcatch
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 Exception
s,
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.
Is it necessary to declare throws IOException
in the method header?