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?
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);
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With