示例:假设我想打开一个文件。如果我得到一个FileNotFoundException
,我需要等待一段时间再试一次。我怎样才能优雅地做到这一点?还是我需要使用嵌套try/catch
块?
例子 :
public void openFile() {
File file = null;
try {
file = new <....>
} catch(FileNotFoundException e) {
}
return file;
}
您可以使用do { ... } while (file == null)
构造。
File file = null;
do {
try {
file = new <....>
} catch(FileNotFoundException e) {
// Wait for some time.
}
} while (file == null);
return file;
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;
}
}
public File openFile() {
File file = null;
while(true){
try {
file = new <....>
} catch(FileNotFoundException e) {
//wait for sometime
}
if(file!=null){
break;
}
}
return file;
}