【问题标题】: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;
}