2

Example: say I want to open a file. If I get a FileNotFoundException, I need to wait for some time and try again. How can I gracefully do that? Or do I need to use nested try/catch blocks?

Example :

public void openFile() {
    File file = null; 
    try {
        file = new <....>
    } catch(FileNotFoundException e) {
    }
    return file;
}

3 Answers 3

5

You could use a do { ... } while (file == null) construct.

File file = null; 

do {
    try {
        file = new <....>
    } catch(FileNotFoundException e) {
        // Wait for some time.
    }
} while (file == null);

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

Comments

3
public File openFile() {
  File file = null; 
  while (file == null) {
    try {
      file = new <....>
    } catch(FileNotFoundException e) {
      // Thread.sleep(waitingTime) or what you want to do
    }
  }
  return file;
}

Note that this is a somewhat dangerous method, since there is no way to break out unless the file eventually appears. You could add a counter and give up after a certain number of tries, eg:

while (file == null) {
  ...
  if (tries++ > MAX_TRIES) {
    break;
  }
}

Comments

1
public File openFile() {
    File file = null; 
    while(true){
      try {
          file = new <....>
      } catch(FileNotFoundException e) {
            //wait for sometime
      }
      if(file!=null){
               break;  
      }
    }
    return file;
 }

Comments

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.