Java尝试三种方法,只有在没有成功的情况下才输入catch块

时间:2016-04-28 16:26:51

标签: java try-catch

尝试使用catch块要求完成步骤

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块)。嵌套的“keep.trying”很少使用。这是因为有更好的风格吗?或者因为程序不应该产生太多的噪音(以很小的成功率拨打电话)?

3 个答案:

答案 0 :(得分:3)

你可以用一些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
}

答案 1 :(得分:2)

这里代码的可读性是关键。这不是一种常见的模式。这也不是一个普通的代码。

这种情况很少见。因此,您不应该专注于简洁,而应该清楚代码。所以你应该写多个catch{try{/*do something*/}{catch{try{/*do something else*/...

答案 2 :(得分:0)

try{
   planA;
}
catch
{
   try
   {
       planB;
   }
   catch
   { 
      try
      {
          planC
      }
   }
}

我认为这是正确的方法

相关问题