thegreatjedi
thegreatjedi

Reputation: 3038

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?

Upvotes: 4

Views: 15442

Answers (6)

Bathsheba
Bathsheba

Reputation: 234785

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

Upvotes: 12

Vineet
Vineet

Reputation: 1

You can also use recursion to do this. But I don't think it would be efficient. Do ... while would be the best approach.

Upvotes: 0

shikhar bansal
shikhar bansal

Reputation: 1679

You can simple use a while loop.

while(!isSuccess){
    try{
        //DO Stuff
    }
}

Upvotes: 1

SomeJavaGuy
SomeJavaGuy

Reputation: 7357

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

Upvotes: 4

Bahramdun Adil
Bahramdun Adil

Reputation: 6089

You can do it with while loop

boolean isSuccess = false;
while(!isSuccess) { // loop till to isSuccess become true
    try {
        ....
        isSuccess = true;
    } catch (Exception e) {
        // Some Exception accrued, you can have 2 options
        // 1. break the loop with break;
        // 2. continue the process
    }
}

Upvotes: 0

lalala la
lalala la

Reputation: 9

I think you should define a maximum of attempts. Otherwise in a worst scenario when all failures occur you app will be frozen.

Upvotes: 0

Related Questions