dushkin
dushkin

Reputation: 2101

JAVA - How to continue a while loop gracefully if one of the functions inside it fails?

I have a function which consists of a while loop. Inside the while loop, I call a number of private methods. If any of the methods fails (returns false, but also throws a private designed exception), I would like to continue strait to the next iteration.

example:

 void func (){

    while (true){

        func1();
        func2();
        func3();

    }
 }

As I said, each func also throws myException object on error.

Thank you!

Upvotes: 3

Views: 1443

Answers (4)

tynn
tynn

Reputation: 39853

You could use the && operator to connect the function calls to not execute any after one of them failed and surround everything with a try-catch block.

void func (){
    while (true){
        try{ func1() && func2() && func3(); }
        catch (YourCustomException e){ }
    }
}

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26961

Catch the exception and decide what to do:

void func (){

    while (true){
        try {
            func1();
        } catch (MyException e) {
            // print error or don't do nothing
        }
        try {
            func2();
        } catch (MyException e) {
            // print error or don't do nothing
        }
        try {
            func3();
        } catch (MyException e) {
            // print error or don't do nothing
        }
    }
 }

Upvotes: 0

K139
K139

Reputation: 3669

Wrap each function() call with a try-catch block. Like

while(true){
    try{
        func1();
    }catch(YourException1 exception){
    //Do something.
    }

    try{
        func2();
    }catch(YourException2 exception){
    //Do something.
    }

    try{
        func3();
    }catch(YourException3 exception){
    //Do something.
    }
}

Upvotes: 5

Kayaman
Kayaman

Reputation: 73558

Put a try-catch block inside the loop.

Upvotes: 1

Related Questions