Java 无法从输入不匹配异常中恢复

Java 无法从输入不匹配异常中恢复,java,exception,exception-handling,Java,Exception,Exception Handling,我正在学习java try catch并使用以下代码 public static void main(String[] args) { Scanner in = null; int i = 0; try { in = new Scanner(System.in); System.out.print("Enter a number: "); i = in.nextInt(); } catch (InputMisma

我正在学习java try catch并使用以下代码

public static void main(String[] args) {

    Scanner in = null;
    int i = 0;

    try {
        in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        i = in.nextInt();
    } catch (InputMismatchException ex) {
        System.out.printf("%nPlease enter a number: %d", in.nextInt());
    } finally {
        if (in != null) {
            System.out.println();
            System.out.println("Finally block !!!");
            in.close();
        }
    }

}
运行这些程序并输入一个字符串,返回带有堆栈跟踪和退出的java(不要求用户输入正确的数字)。 如果我在catch块中移除in.nextInt(),我看不到堆栈跟踪,但也不会要求用户输入-立即退出


我想不出我的代码出了什么问题

最终尝试捕获
块的工作原理如下:

  • 执行
    try
    块中的代码,在这种情况下,让用户输入一些内容
  • 如果抛出了
    catch
    中指定的异常,则只执行
    catch
    块中的代码一次
  • 最后执行
    块中的代码
  • 如果要等待用户输入
    int
    ,则应使用
    for
    while
    循环:

    Scanner in = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int i;
    
    while (true) {
        try {
            i = Integer.parseInt(in.nextLine());
            System.out.println("Your input is " + i);
            break;
        } catch (NumberFormatException exception) {
            System.out.println("Please enter a number:");
        }
    }
    

    try-catch块不是一个循环。顺便说一下,您不应该将异常处理作为实现逻辑的一部分。它用于处理超出您预期的异常情况。请阅读
    nextInt
    的javadocs。如果方法调用抛出
    inputmaschException
    ,它不会跳过组成它无法作为整数解析的标记的字符。因此,如果您再次调用
    nextInt
    ,您将尝试再次将同一标记解析为整数。。。然后再次失败。@user3437460-如果OP的目标是了解异常/处理程序是如何工作的,那么这很好。此外,如果没有大量的上下文,很难判断某件事是否是“例外情况”。比我们这里有更多的上下文。Doem-还可以查看您的
    printf
    实际上在做什么。它(试图)读取一个数字,然后将该数字插入要求输入数字的消息中。那是不对的。。。是的。为什么要使用
    Integer.parseInt(in.nextLine())
    而不是.nextInt()中的
    ?@J.Doem看到了吗