[英]Java try three methods and enter catch block only if none succeeded
尝试捕获块要求执行步骤
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”。 是因为有更好的风格吗? 还是因为程序不应该产生太多的噪音(以较低的成功率进行调用)?
您可以编写一种方法来使用一些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
}
在这里,代码的可读性是关键。 这不是常见的模式。 它也不是司空见惯的代码。
这种情况很少见。 因此,您不应该将重点放在简洁上,而应该使代码清晰。 因此,您应该编写多个catch{try{/*do something*/}{catch{try{/*do something else*/...
try{
planA;
}
catch
{
try
{
planB;
}
catch
{
try
{
planC
}
}
}
我认为这是正确的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.