I have created a sample file reading program as an exercise while learning how to implement good exception handling. I want to ask: is this a good approach or is there some other solution that I am not aware of?
import java.util.*; // Needed for Scanner and InputMismatchException
import java.io.*; // Needed for FileReader and FileNotFoundException
/**
* This class reads two numbers from a file and
* print their sum.
*/
public class ReadNum
{
public static void main (String[] args)
{
Scanner inFile = null;
try
{
int num1, num2; // To hold numbers read from the file
int sum; //To hold sum
// Create the scanner object for file input.
inFile = new Scanner(new FileReader("sample.txt"));
// Read numbers from the file.
num1 = inFile.nextInt();
num2 = inFile.nextInt();
// Calculate total.
sum = num1 + num2;
// Print total.
System.out.println("sum " + sum);
}
catch (FileNotFoundException ex)
{
System.out.println("Error "+ ex);
}
catch (InputMismatchException ex)
{
System.out.println("Error "+ ex);
}
catch (Exception ex)
{
System.out.println("Error "+ ex);
}
finally
{
// Close the file.
if(inFile != null)
inFile.close();
}
}
}