0

I'm creating a program that opens and then reads files which users have specified, currently the code I have looks like:

    System.out.println("Enter the name of the file you want to open: ");
    FileN = scan.nextLine();
    // I want the program to return to this point here if an error has occured.
    try
    {
        scan = new Scanner(new File (FileN));
    }
    catch(Exception e)
    {
        System.out.println("Could not find file" + e);
        System.out.println("Please enter a valid file name: ");

    }

I have specified above where I want the program to return to within the code, I have currently tried creating a loop and then using continue however it wont let me put a try within the loop. Also I've tried to create a new void and it still wont work. Currently the program continues to run even if the user has entered an invalid file name.

I have searched for an answer already and can only find this relating to what I want: Java - Exception handling - How to re-enter invalid input

Also clarifying what I mean by putting a try in a loop; yes, it is possible. However I want to know whether for the continue to work in my program, do I put the try inside the loop or the loop inside the try? I have referred to: Should try...catch go inside or outside a loop?

This is the error I'm currently getting with my latest code

halfer
  • 19,824
  • 17
  • 99
  • 186
m1ddleware
  • 78
  • 2
  • 16

3 Answers3

2

Your problem is that your order of operations is bad. Here is your order:

  • Process a file
  • Give an error when the file doesn't exist
  • Ask for a new file name

I suggest this approach:

  • Ask for a file name
  • Check whether the file exists
  • If it doesn't exist, ask again
  • Process the file

In a nutshell, my approach is:

  • Read some input
  • Validate the input. If it's bad do some error handling
  • Process the input further

Coming back to your problem: Create a loop which asks for file names until File.exists() returns true. Maybe also check File.isFile() (so people can't enter directories).

Create the scanner only after the loop. It will still throw an exception (Java doesn't know that you've already made sure the file exists). But the exception handler code won't need to ask for a file name (so no loop there).

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Exactly. Exceptions are for *exceptional* conditions. A user entering an invalid file is not exceptional. – Michael Nov 06 '17 at 13:30
  • So I have currently re-ordered my order of operations as advised however it wont allow me to catch the FileNotFoundException, therefore just keeps requesting for the user to enter input. – m1ddleware Nov 06 '17 at 13:45
  • Try harder or explain in detail why you can't catch the exception. – Aaron Digulla Nov 28 '17 at 13:15
0

It becomes a little easier if you use Exception in the sense it's meant to be used, to handle something unexpected. A file not existing isn't really an exception as it is to be expected. A file existing but not being able to be opened, or being opened but has zero content even though it has 1MB content is something unexpected, so is an Exception. Taking into account the expected behaviour of a file not existing (as it's being typed in by a user, who may type it incorrectly), you could use something like:

boolean fileExists = false;
File newFile;
while(!fileExists) {
  System.out.println("Enter the name of the file you want to open: ");
  FileN = scan.nextLine();
  newFile = new File(FileN);
  fileExists = newFile.exists();
  if (!fileExists) {
    System.out.println(FileN + " not found...");
  }
}
try {
    Scanner scan;
    scan = new Scanner(newFile);
    ... do stuff with the scanner
}
catch(FileNotFoundException fnfe) {
  System.out.println("sorry but the file doesn't seem to exist");
}
codebrane
  • 4,290
  • 2
  • 18
  • 27
  • How can I catch the FileNotFoundException, as this is currently showing an error within the code. If I throw FileNotFoundException, the program works however it doesn't notify the user that the file cannot be found or an error has been made, it just keeps requesting for the user to enter input. – m1ddleware Nov 06 '17 at 13:43
  • There is no FileNotFoundException as exists() doesn't throw it. I've updated the code to show a message to the user telling them the file doesn't exist. You don't need any exceptions to be thrown or caught before you reach the Scanner. – codebrane Nov 06 '17 at 13:52
  • please check image I have included in my question. – m1ddleware Nov 06 '17 at 14:03
  • As you're designing well, not relying on exceptions for non exceptional things you've run into the problem of Java itself regarding a file not existing as an exception. I've updated the code to show how to handle it. This might occur if another process is cleaning out directories and you find the file but in the few milliseconds it takes to call the scanner, the file has been deleted! Note how the catch block is at the end of the program and you use the scanner in the try block. The try block is the "success" route. The catch blocks are where you handle things that aren't "success" – codebrane Nov 06 '17 at 14:45
  • Thank you, this works perfectly now. Tested multiple times, successful on each. – m1ddleware Nov 06 '17 at 15:00
-1

You can try a while loop:

        boolean again =true;

    while(again){
     FileN = scan.nextLine();

            try
            {
                scan = new Scanner(new File (FileN));
                again=false;
            }
            catch(Exception e)
            {
                System.out.println("Could not find file" + e);
                System.out.println("Please enter a valid file name: ");

            }}
SF23
  • 174
  • 1
  • 12