Common Pitfalls with break and continue
You'll learn to spot and avoid three frequent mistakes that trip up beginners when using break and continue in loops.
What Are These Pitfalls?
Even though break and continue are powerful tools, they can create subtle bugs if you're not careful. The most common mistakes involve unreachable code, accidental infinite loops, and misunderstanding label scope.
Pitfall #1: Unreachable Code After break
Placing any statement immediately after break in the same block makes that code unreachable—the compiler will catch this error:
while (true) {
break;
System.out.println("This will never execute"); // Compiler error!
}
Think of it like this: break is an emergency exit door. Nothing after the exit in that room matters because you've already left.
Pitfall #2: Misplaced continue Creating Infinite Loops
If you use continue before updating your loop control variable, you might skip the update entirely:
int i = 0;
while (i < 5) {
if (i == 2) {
continue; // Skips i++ below—infinite loop!
}
System.out.println(i);
i++;
}
The loop gets stuck at i == 2 forever because the increment never happens.
Pitfall #3: Label Scope Errors
Labels only work with enclosing loops. You can't break or continue to a label that isn't surrounding your current position:
outer:
for (int i = 0; i < 3; i++) {
}
// break outer; // Error: label is out of scope here
Labels exist only within their loop's scope—you can't reference them from outside.
Avoiding These Mistakes
Always verify: Where does control flow go after your break or continue? Will loop variables still update correctly? Is your label actually wrapping the statement?
Key Takeaway: Watch for unreachable code after break, ensure loop updates happen before continue, and verify labels enclose the statements that reference them.