3

The following code calculates the average of numbers that are stored in a text file. I have added some exception handling for "file not found" errors. I need to know how to add another exception for when the data in the text file is not numeric (or not int). I thought about adding multiple catches. Not sure how though?

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

public class NumAvg2 {

    public static void main(String[] args)
    {
    int c = 1;  
    long sum = 0;
    String strFileName;

    strFileName = args[0];

    Scanner scFileData;
    try{
        scFileData = new Scanner (new File(strFileName));

        while (scFileData.hasNext())
        {
            sum = sum + scFileData.nextInt();
            c++;
        }

    scFileData.close();
    System.out.println("Number of integers: " + (c - 1)); 
    System.out.println( "Average = " + (float)sum/(c - 1));

    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
        System.exit(1);
    }

  } 
}   
1
  • you could read a string and try parsing. not good parsing well rays a error Commented Sep 26, 2012 at 19:17

7 Answers 7

6

You can use Java 7's multi catch if you want

try {
...
}
catch (FileNotFoundException|InputMismatchException ex) {
//deal with exception
}

This is a bit cleaner than multiple catches. If either of these exceptions is thrown it is caught in the single catch block

Sign up to request clarification or add additional context in comments.

4 Comments

This works: } catch (FileNotFoundException|InputMismatchException e) { System.out.println("Error Occured!"); System.out.println(e.getMessage()); System.exit(1); }
This is pretty...+1 for the new feature
@FAUZIRASHID When you catch an exception, never just print your own message. Always print the one that comes with the exception. Otherwise you have no hope of knowing what the actual error was.
@FAUZIRASHID, EJP makes a very good point. Also if it works then it is good etiquette to accept the answer...
3
} catch (InputMismatchException e) {
    System.out.println("Not integer!");
    System.exit(1);
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
    System.exit(1);
}

Comments

3
...
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
    System.exit(1);
} catch (InputMismatchException e) {
    // Add stuff into your new exception handling block
}
...

Your IDE may have not complained about this because InputMismatchException is a RuntimeException (unchecked exception), while FileNotFoundException is a regular checked Exception.

1 Comment

} catch (InputMismatchException e) { // Add stuff into your new exception handling block }
3

Note that Scanner.nextInt also throws an InputMismatchException if the next token isn't an integer.

From the docs:

Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

InputMismatchException is a RuntimeException, and so can be ignored in a try/catch block, but you can also explicitly handle it:

try
{
    // ... Scanner.nextInt
}
catch (FileNotFoundException e)
{
    System.out.println("File not found!");
    System.exit(1);
}
catch (InputMismatchException e)
{
    // ... not an int
}

Comments

2

To catch multiple exceptions, you chain them like so:

public class NumAvg2 {

public static void main(String[] args)
{
int c = 1;  
long sum = 0;
String strFileName;

strFileName = args[0];

Scanner scFileData;
try{
    scFileData = new Scanner (new File(strFileName));

    while (scFileData.hasNext())
    {
        sum = sum + scFileData.nextInt();
        c++;
    }

scFileData.close();
System.out.println("Number of integers: " + (c - 1)); 
System.out.println( "Average = " + (float)sum/(c - 1));

} catch (FileNotFoundException e) {
    System.out.println("File not found!");
    System.exit(1);
} catch(InputMismatchException e){
    //handle it
}
} 
}

Comments

1
} catch (FileNotFoundException | InputMismatchException e) {
    e.printStackTrace();
    System.exit(1);
}

Comments

1

Where are you converting your data from file to integer?? You should add one try-catch there..

Instead of using the below while loop, where you have to catch the exception for TypeMismatch: -

    while (scFileData.hasNext()) {
        try {
            sum = sum + scFileData.nextInt();
            c++;
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input");
        }
    }

You can use a variation like the one below: -

    while (scFileData.hasNextInt())
    {
        sum = sum + scFileData.nextInt();
         c++;
    }

scanner.hasNextInt() will automatically check whether input in integer or not..

Also, as you are declaring your variable outside your try-catch block.. I would suggest not to use a big try-catch block..

Rather you can surround file reading statement around a try-catch (That would be one statement).. Then after a few statements, you can again surround your scanner.nextInt() around another try-catch..

So, I would modify your code like this: -

public class NumAvg2 {

public static void main(String[] args)
{
    int c = 1;  
    long sum = 0;
    String strFileName;

    strFileName = args[0];

    Scanner scFileData;

    try{
        scFileData = new Scanner (new File(strFileName));

    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
        System.exit(1);
    }
    while (true) {
        if (scFileData.hasNextInt())
        {
            sum = sum + scFileData.nextInt();
            c++;
            break;
        } else {
            System.out.println("Enter an integr");
        }
    }

    scFileData.close();
    System.out.println("Number of integers: " + (c - 1)); 
    System.out.println( "Average = " + (float)sum/(c - 1));

}
}

This way your code becomes more cleaner.. * Just a Suggestion..

4 Comments

OK. I got it to work using this method too. Added 2nd try/catch in the loop, but you have to also have to put a System.exit(1);
You don't need now.. see that I have used scanner.hasNextInt() in while.. It will automatically handle it.. It will only go inside the while if number is an integer..
See modified code.. I used an if now.. You don't need to do System.exit(1) if input is not an integer.. Just ask for input until an Integer is given..
Interesting way of doing it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.