Reputation: 3
I recently rediscovered the use of breaking back to a label. Now I'm wondering if it is possible to break back to a label from another class.
Example of what i want:
label:
for (Product p : ProductList) {
if (p.getSet() == true) {
classHandler();
}
}
someFunction() {
break label;
}
While I was typing this I actually tried making a local function in my Main
class (so I could just call that function instead) but even there I got the undefined label: label
error.
Upvotes: 0
Views: 791
Reputation: 330
It doesn't make sense, since there is no guarantee that label exists, not even that someFunction() is called within a loop.
Upvotes: 0
Reputation: 262842
No, you cannot. That does not even work between two methods of the same class. Labels are scoped (at the most) within a single method.
Upvotes: 0
Reputation: 7054
The label that you break to must be in scope. From the java sun documentation:
A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a while, do, for, or switch statement. A break statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps
Upvotes: 1
Reputation: 308269
No, you can't. And you shouldn't.
If the condition for breaking is some problem, then throwing an exception would be the correct approach.
Otherwise you should do something like returning a flag that indicates if other products should still be handled and reacting on that in your loop.
As you noticed you can't even break
through method-borders, and that's a good thing. break
and continue
are powerful tools, but can easily make your code confusing, if used in the wrong way. For example a break
hidden inside a huge code block can be easy to miss, but if you use a continue
at the very top of a method to skip an iteration based on some condition, then the intention is pretty clear.
Upvotes: 5