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

I have a function that consists of a while loop. Inside the while loop, I call several private methods. If any of the methods fail (returns false, but also throws an exception from a private exception), I would like to continue moving to the next iteration.

Example:

 void func (){

    while (true){

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

    }
 }

      

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

Thank!

+3


source to share


4 answers


Wrap the call to function () with a try-catch block. how



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

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

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

      

+5


source


Place a try-catch block inside a loop.



+1


source


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

      

0


source


You can use a statement &&

to wire up your function calls so they don't get executed after one of them has failed, and combine everything with a try-catch block.

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

      

0


source







All Articles