Reputation: 3038
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
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
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
Reputation: 1679
You can simple use a while loop.
while(!isSuccess){
try{
//DO Stuff
}
}
Upvotes: 1
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
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
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