Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "retry" a try-catch?

In my code, I will attempt a certain task in a try-block. If exceptions are thrown, the catch-blocks will rectify the errors encountered (usually prompting for correct input). After that, the program is supposed to try again repeatedly until success is achieved. My current code is as follows:

for (bool isSuccess = false; !isSuccess;) {
    try {
        ...
        isSuccess = true;
    }
    // catch blocks here to correct any exceptions thrown
}

As can be seen, I'm currently using a loop structure to make the try-catch block start over if the try block fail, until the try block succeeds completely. Is there a more elegant solution?

like image 849
thegreatjedi Avatar asked Dec 03 '22 15:12

thegreatjedi


2 Answers

I'd prefer to see a do loop that exits by default (then there is less chance of encountering an infinite loop). Your use of the boolean type only really mimics the behaviour of break and continue. As an alternative, perhaps more natural way, consider

do {
    try {
        // some code 
    } catch (/*whatever*/){
        continue; // go again
    }
    break;
} while (true);
like image 153
Bathsheba Avatar answered Dec 16 '22 09:12

Bathsheba


Just to give you an alternative, and if your code allows you to do so, then you could also use recursion. But in my eyes this is less favorable compared to the other ways to solve this.

public void doSomething() {
    try {
       ...
    } catch(Exception e) {
       doSomething();
    }
}
like image 20
SomeJavaGuy Avatar answered Dec 16 '22 11:12

SomeJavaGuy