尝试 catch block 要求执行步骤
try {
step a;
step b;
step c;
} catch {
System.out.print("one of the steps failed");
}
如果我有计划 A、计划 B 和计划 C,并且我想连续尝试每个计划,该怎么办
keep.trying{
plan A;
plan B;
plan C;
} catch {
System.out.print("None of the plans worked");
}
一个人能做到
boolean done=false;
try {
planA();
done=true;
}catch{// :|}
if (done!=true){
try {
planB();
done=true;
}catch{// :(}
if (done!=true){
try{
planC();
}catch{ System.out.print("Failed"); }
if (done == true){ System.out.print("Success") };
<小时/>
这更像是一个好/坏风格的问题。 “尝试执行至少一个命令或抛出异常”是一种常见现象(try/catch block )。很少使用嵌套的“keep.trying”。这是因为有更好的风格吗?或者因为程序不应该产生太多噪音(以较小的成功率进行调用)?
最佳答案
您可以编写一个方法来使用一些 lamda 来实现这一点。
@FunctionalInterface
public interface Plan {
public void execute() throws Exception;
}
public static boolean tryAll(List<Plan> lst) {
for(Plan p : lst) {
try {
p.execute();
return true; //If we reach this line, p succeeded
} catch (Exception e) {
//This plan failed
}
}
return false; //All plans failed
}
或者:
@FunctionalInterface
public interface Plan {
public boolean execute();
}
public static boolean tryAll(List<Plan> lst) {
for(Plan p : lst) {
if(p.execute()) return true;
}
return false; //All plans failed
}
关于Java尝试三种方法,仅当没有成功时才进入catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920397/