Re: do loop bug?
emrefan wrote:
Does this program below indicate to you that there's a bug in java's do
loop. Or is it just one of those many traps that I've fallen into and
I've only got myself to blame? I was expecting the two loops would
behave much the same. Have I been bitten by the optimizer?
public class DoLoopBug {
public static void main( String[] args ) {
int retryCnt = 0;
doLoop1: do {
try {
if (retryCnt < 3)
throw new java.net.ConnectException();
break;
}
catch (Exception e) {
System.out.println( "caught exception; retryCnt=" +
retryCnt );
if (++retryCnt < 20)
continue doLoop1;
}
} while (false);
System.out.println( "after doLoop1, retryCnt = " + retryCnt +
"\n" );
retryCnt = 0;
doLoop2: do {
try {
if (retryCnt < 3)
throw new java.net.ConnectException();
break;
}
catch (Exception e) {
System.out.println( "caught exception; retryCnt=" +
retryCnt );
if (++retryCnt < 20)
continue doLoop2;
}
} while (true); // Here's difference from DoLoop1
System.out.println( "after doLoop2, retryCnt = " + retryCnt );
}
}
The results I get are:
caught exception; retryCnt=0
after doLoop1, retryCnt = 1
caught exception; retryCnt=0
caught exception; retryCnt=1
caught exception; retryCnt=2
after doLoop2, retryCnt = 3
which is what I expected.
Each continue effectively jumps to its loop's while expression
evaluation. For the first loop, the expression evaluates to false, so it
falls through first time.
For the second loop, the while expression evaluates to true, so it does
another iteration. That goes on until retryCnt reaches 3, and the break
is executed instead of the throw leading to a continue.
If this does not answer your question, perhaps you could explain why you
expected the two loops to behave the same?
Patricia