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

Chr*_*ris 2 java exception file try-catch

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

示例:

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

aio*_*obe 5

你可以使用一个do { ... } while (file == null)构造.

File file = null; 

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

return file;
Run Code Online (Sandbox Code Playgroud)