首页 > 解决方案 > 可以在 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;
        }

反正有没有实现类似的功能?上面的代码是一个例子。

标签: javaexceptionnullpointerexceptionlabel

解决方案


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);

推荐阅读