是否可以在 catch 块中访问在 try 块中定义的标签?


try {
do {
input: if (choice2 != null)
System.out.println("Please enter a valid choice");
choice2 = reader.readLine();
} while ((int) choice2.charAt(0) >= 65 && (int) choice2.charAt(0) <= 69);
} catch (StringIndexOutOfBoundsException e) {
continue input;
}

无论如何可以实现类似的功能吗?上面的代码是一个示例。

try-catch移动到循环中。您可能打算标记循环。而且,即使它们是可选的,也要使用大括号。喜欢

input: do {
try {
if (choice2 != null) {
System.out.println("Please enter a valid choice");
}
choice2 = reader.readLine();
} catch (StringIndexOutOfBoundsException e) {
continue input;
}
} while ((int) choice2.charAt(0) >= 65 && (int) choice2.charAt(0) <= 69);

最新更新