2

示例:假设我想打开一个文件。如果我得到一个FileNotFoundException,我需要等待一段时间再试一次。我怎样才能优雅地做到这一点?还是我需要使用嵌套try/catch块?

例子 :

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

3 回答 3

5

您可以使用do { ... } while (file == null)构造。

File file = null; 

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

return file;
于 2012-07-03T12:53:27.317 回答
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;
}

请注意,这是一种有些危险的方法,因为除非文件最终出现,否则无法破解。您可以添加一个计数器并在尝试一定次数后放弃,例如:

while (file == null) {
  ...
  if (tries++ > MAX_TRIES) {
    break;
  }
}
于 2012-07-03T12:54:16.270 回答
1
public File openFile() {
    File file = null; 
    while(true){
      try {
          file = new <....>
      } catch(FileNotFoundException e) {
            //wait for sometime
      }
      if(file!=null){
               break;  
      }
    }
    return file;
 }
于 2012-07-03T12:53:39.890 回答