2012-07-03 67 views
2

示例:說我想打開一個文件。如果我得到FileNotFoundException,我需要等一段時間再試。我該如何優雅地做到這一點?或者我需要使用嵌套try/catch塊?如果拋出異常,Java繼續執行循環

例子:

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

回答

5

你可以使用一個do { ... } while (file == null)結構。

File file = null; 

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

return file; 
+0

謝謝,這是那麼容易:)呵呵 – Chris

+0

..是啊。別客氣。 – aioobe

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