Java尝试三种方法,仅当没有成功时才进入catch block

标签 java try-catch

尝试 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/

相关文章:

java - Wordnet::相似度服务器:如何从 Java 与其对话?

r - 错误打破for循环: conditional try statement?

java - JAVA中的异常处理及throws语句的使用

java - IntelliJ IDEA javadoc F1

php - 在 PHP 中使用 odbc_exec 时使用 try-catch 语句的意外行为

C++ 异常处理器 : terminate ist always called

php - 空目录错误处理

java - 数组中有多少个不同的值

java - Azure 连接无法连接证书错误

java - Android中的字节数据类型内存大小