labled break. , GOTO. break; / .. : .
. , "Jump-Condition" . , , .
If your method is called getDrink () and it returns a milk object, that's fine. But if your method is called "getWater ()", it should throw an exception instead of returning milk ...
So, instead of:
public class TestBad {
public static void main(String[] args) {
String[] guys = {"hans", "john"};
myLabel: {
for(String guy: guys) {
String drink = getDrink(guy);
if(drink.equals("milk")) {
break myLabel;
}
}
}
}
private static String getDrink(String guy) {
if(guy.equals("hans"))
return "milk";
else
return "water";
}
}
You should use:
public class TestGood {
public static void main(String[] args) {
String[] guys = {"hans", "john"};
try {
handleStuff(guys);
} catch (Exception e) {
}
}
private static void handleStuff(String[] guys) throws Exception {
for(String guy: guys) {
String drink = getWater(guy);
}
}
private static String getWater(String guy) throws Exception {
if(guy.equals("hans"))
throw new Exception("No Water there!");
else
return "water";
}
}
Fazit: Instead of nesting blocks in blocks or multiple loops, you need to nest methods and use the correct exception handling. This improves readability and reuse.
source
share