0

I am receiving this error on the last line of code when returning the scanner. I cannot use a throw so I need to keep the try catch in the code.

public static Scanner getInputScanner(Scanner console) {
    boolean inputTest = true;
    File inputFile = null;
    System.out.print("Enter input file: ");
    while(inputTest){
        try{
            inputFile = new File(console.next());
            Scanner input = new Scanner(inputFile);
            inputTest = false;
        }catch (FileNotFoundException e) {
            System.out.println("File does not exist");
            System.out.print("Enter new input file: ");   
            inputTest = true; 
            continue;
        }
    }
    return new Scanner(inputFile);
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117
number01
  • 19
  • 3
  • Hi, I've rolled your edit back because it removed the useful portions of the question, thus invalidating the answers provided. Please feel free to make edits to clarify it, but please also refrain from changing it in a way that defaces it or makes existing answers invalid, out of respect to the authors to those answers. – nanofarad Jul 06 '20 at 22:48

4 Answers4

0

You can use try With Resources to read the file.The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them. To do so, you must open and use the resource within a Java try-with-resources block. When the execution leaves the try-with-resources block, any resource opened within the try-with-resources block is automatically closed, regardless of whether any exceptions are thrown either from inside the try-with-resources block, or when attempting to close the resources

public static Scanner getInputScanner(Scanner console) throws IOException {

try (FileInputStream fileInputStream = new FileInputStream(console.next())) {
  return new Scanner(fileInputStream);

} catch (FileNotFoundException exception) {
  exception.printStackTrace();
}
return null;

}

Java Try with Resources

Ramesh KC
  • 570
  • 7
  • 30
0

Well, according to how your code is set up, it seems like that inputFile has to exist, and the FileNotFoundException should never actually be thrown anyways. Regardless, the rules of Java state that a checked exception such as FileNotFoundException must be caught or declared thrown, and as you said you cannot use throws in the declaration, I'd just wrap a try-catch around it:

try {
    return new Scanner(inputFile);
}
catch(FileNotFoundException e) {
    throw new RuntimeException("File does not exist; this should never happen");
}

In the catch block I threw a RuntimeException instead. This is because if you leave it blank, it won't compile as every branch has to return a value or result in an exception. And as RuntimeException is an unchecked exception, I don't need to catch it or declare it to be thrown.

Alternatively, you could also return null;, and since it should never happen anyways it doesn't matter much. However, if something goes horribly wrong and the file does end up not existing, having a RuntimeException will make the error a lot easier to find than a NullPointerException from returning null. (See How to deal with checked exceptions that cannot ever be thrown)

Side note: If I read the code correctly, I assume you're trying to see if the file exists with Scanner input = new Scanner(inputFile); in the while loop. This is not good practice. Use inputFile.isFile() to check if it exists instead.

Tyler Tian
  • 597
  • 1
  • 6
  • 22
  • What if I cannot use throw anywhere inside the code including inside the try catch? – number01 Jul 06 '20 at 17:08
  • @number01 if you're not allowed to use the `throw` keyword at all (even though the program would work just fine since `RuntimeException` is unchecked), you could simply just `return null` in the `catch` clause (since you have to return a value from the function). It's not considered the best thing to do for this situation but it would work nonetheless. – Tyler Tian Jul 07 '20 at 03:15
0

A simple way to work around the issue is to return the Scanner that you create in the loop rather than creating a redundant instance outside the loop.

public static Scanner getInputScanner(Scanner console) {
    boolean inputTest = true;
    File inputFile = null;
    System.out.print("Enter input file: ");
    Scanner input;
    while(inputTest){
        try{
            inputFile = new File(console.next());
            input = new Scanner(inputFile);
            inputTest = false;
        }catch (FileNotFoundException e) {
            System.out.println("File does not exist");
            System.out.print("Enter new input file: ");   
            inputTest = true; 
            continue;
        }
    }
    return scanner;
}
Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
0

Instead of trying to open the file, you can check for its existence:

public static Scanner getInputScanner(Scanner console) {
    boolean inputTest = true;
    File inputFile = null;
    System.out.print("Enter input file: ");
    while(inputTest){
      inputFile = new File(console.next());
      if (inputFile.exists()) {
        inputTest = false;
    }
    return new Scanner(inputFile);
}

The NIO2 API (Files, Path) may provide more checks, such as checking if you can read the file.

NoDataFound
  • 11,381
  • 33
  • 59