【问题标题】:Java continue executing loop if exception was throwd如果抛出异常,Java 继续执行循环
【发布时间】:2012-07-03 12:51:37
【问题描述】:

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

例子:

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

【问题讨论】:

    标签: java file exception try-catch


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      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;
        }
      }
      

      【讨论】:

        【解决方案3】:
        public File openFile() {
            File file = null; 
            while(true){
              try {
                  file = new <....>
              } catch(FileNotFoundException e) {
                    //wait for sometime
              }
              if(file!=null){
                       break;  
              }
            }
            return file;
         }
        

        【讨论】:

          猜你喜欢
          • 2012-04-07
          • 2012-03-08
          • 1970-01-01
          • 2015-10-31
          • 1970-01-01
          • 1970-01-01
          • 2019-01-15
          • 1970-01-01
          • 2021-05-13
          相关资源
          最近更新 更多