2016-04-28 36 views
0

try catch块请求要经过的步骤的Java尝试三种方法并只,如果没有成功

try { 
    step a; 
    step b; 
    step c; 
} catch { 
    System.out.print("one of the steps failed"); 
} 

catch块如果我有计划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”很少使用。这是因为有更好的风格吗?或者因为一个程序不应该产生太多的噪音(以很小的成功率打电话)?

+1

您对实际问题的描述过于模糊,无法给出具体的建议。但是,如果您想要的是对您所拥有的解决方案的更通用的解决方案,则只需一个操作成功即可停止的循环。 –

+0

这听起来有点像你试图用异常来表示失败方法的失败。如果是这样,那就是糟糕的风格。更好的风格是让他们返回一个成功/失败的标志,甚至是一个布尔值,这将使得它非常容易链接。 – CPerkins

回答

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

似乎OP可能只是让函数返回true/false而不是抛出异常。 if(p.execute){return true;)},然后在末尾返回false如果它们都不起作用 –

+1

这也是如此。从他的原始代码看来,“计划”可能会引发异常,但是您可以轻松修改它以使用返回值。 – Mshnik

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

我认为这是做这

+0

我认为这是非常糟糕的风格,因为范围越深,越有计划! – loonytune

+0

@ loonytune我的问题是什么使它成为一种不好的风格,什么是一种好的风格?另外,有什么警告? – Stepan

2

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

这种情况很少见。所以你不应该把注意力放在简洁,而是代码应该清晰。所以你应该写多个catch{try{/*do something*/}{catch{try{/*do something else*/...

相关问题