如果抛出异常,Java继续执行循环

时间:2012-07-03 12:51:38

标签: java file exception try-catch

示例:说我要打开一个文件。如果我得到FileNotFoundException,我需要等待一段时间再试一次。我怎么能优雅地做到这一点?或者我是否需要使用嵌套的try/catch块?

示例:

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

3 个答案:

答案 0 :(得分:5)

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

File file = null; 

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

return file;

答案 1 :(得分: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;
  }
}

答案 2 :(得分:1)

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