Stepan
Stepan

Reputation: 1431

Java try three methods and enter catch block only if none succeeded

Try catch block asks to go through steps

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

What if I have plan A, plan B and plan C and I want to try each plan in a row

keep.trying{
    plan A; 
    plan B; 
    plan C;
} catch {
    System.out.print("None of the plans worked");
}

one can do

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") };

This is more of a good/bad style question. "try to execute at least one command or throw exception" is a commonplace (try/catch block). Nested "keep.trying" are rarely used. Is this because there is a better style? Or because a program shouldn't produce too much noise (make calls with small success rate)?

Upvotes: 0

Views: 96

Answers (3)

SoLongAndTFATF
SoLongAndTFATF

Reputation: 43

Here readability of the code is key. This isn't a common pattern. Neither is it a commonplace code.

This situation is rare. So you shouldn't focus on it being concise, rather the code should be clear. So you should write multiple catch{try{/*do something*/}{catch{try{/*do something else*/....

Upvotes: 2

Mshnik
Mshnik

Reputation: 7032

You could write a method to do that with a bit of lamda usage.

@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
}

Alternatively:

@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
}

Upvotes: 3

Arjun Bala
Arjun Bala

Reputation: 287

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

I think this is proper way to do this

Upvotes: 0

Related Questions