tzwickl
tzwickl

Reputation: 1371

How to handle a FileNotFoundException?

I'm tinkering around on a small application to read some numbers in from a file. Everything runs well so far, but now I have encountered a problem I don't know how I can effectively fix it. If the user enters, unintentionally maybe, the wrong filename a FileNotFoundException will be thrown by the JVM, that I catch in my invoking method. Now I want to give him (the user) two another tries to enter the correct filename, but I don't know how I can invoke the method again which is opening the file when I'm actually in the catch-block below. I will illustrate my transient solution below, but I'm not really sure if this is the most effective/elegant way to solve this problem:

//code omitted
            int temp = 0;

        while(true) {
            filename = input.next();

            try {
                ex.fileOpen(filename);
            }
            catch(FileNotFoundException e) {
                if(temp++ == 3) {
                    System.err.println("You have entered the filename three times consecutively wrongly");
                    return;
                }
                continue;
            }
            break;
        }
//do some other stuff

input is a scanner which reads the user input and assigns it to the String-variable filename. fileOpen is a method which takes a filename, opens the file, reads the content and write all numbers in a vector.

So, I would really appreciate every support from the more experienced java programmers.

Greetings Tom

Upvotes: 0

Views: 5673

Answers (6)

confusopoly
confusopoly

Reputation: 1245

How about something like this (pseudocode, not executable)?

// ...
    for(int i = 0; i < 3; i++)
    {
        // User interaction to get the filename

        if(attemptToOpenFile(ex))
        {
            break;
        }
    }
    // Check if the file is open here and handle appropriately.
// ...
}

bool attemptToOpenFile(File ex, String filename) { // Forgot the class name for this
    try {
        ex.fileOpen(filename);
        return true;
    } catch(FileNotFoundException e) {
        return false;
    }
}

Alternatively, check if the file exists before calling fileOpen().

Upvotes: 0

Jiri Kremser
Jiri Kremser

Reputation: 12857

You may want to recursively call the method again:

  public void doTheStuff(int attemptsLeft)
      // ...
      if (attemptsLeft == 0) {
         System.err.println("You have entered the filename three times consecutively wrongly");
         return;
      }
      filename = input.next();
      try {
          ex.fileOpen(filename);
      }
      catch(FileNotFoundException e) {
          doTheStuff(attemptsLeft - 1);
          return;
      }
      // ...
  }

then simply call doTheStuff(3)

Upvotes: 1

Ricardo Mogg
Ricardo Mogg

Reputation: 589

Do not use exceptions to control your WorkFlow. Try something like this:

 final int MAX_ERROR_ALLOWED=3;
public void readFile(String filename, int errorCount){
     try{
       File f = new File(filename);
       if(!f.exists()){
          String newFilename = input.next();
          if(errorCount>=MAX_ERROR_ALLOWED){
              throw new JustMyException();
          }
          readFile(newFilename, errorCount++);   
       }else{
           //whatever you need to do with your file
       }
     }
}

Upvotes: 0

Scott Allen
Scott Allen

Reputation: 533

Think this will work.

    int x = 0;
    while (true){
       filename = input.next();

       try{
          ex.fileOpen(filename);
          break;  // If it throws an exeption, will miss the break
       }catch(FileNotFoundException e){
          System.err.println("File not found, try again.");  
       }
       if (x==2){
          System.errprintln("You have entered the wrong file 3 times");
          System.exit(0);
       }
       x++
    }

Upvotes: 0

user2463094
user2463094

Reputation:

You could use something like this,

public class AppMain {

  public static void main(String[] args) throws IOException {
    String filePath = input.next();

    InputStream is = getInputStream(filePath);
    int temp = 0;

    while(is == null && temp < 3){
      filePath = input.next();
      is = getInputStream(filePath);
      temp++;
    }

    if(is == null){
      System.err.println("You have entered the filename three times consecutively wrongly");
      return;
    }

    .........
    .........

  }

  private static InputStream getInputStream(String filePath){
    InputStream is = null;

    try{
      is = new FileInputStream(filePath);
      return is;
    }catch (IOException ioException) {
      return null;
    }
  }
}

Upvotes: 1

Anton
Anton

Reputation: 6061

You can use exists method of the File class

For example fileOpen method can return true/false whether file exists

Upvotes: 0

Related Questions