异常处理,捕获原因导致while循环停止

3
我有一个需要阅读的文件,需要打印整数,捕获异常并继续显示下一个整数,直到没有更多整数为止。
文件包含:12 5 sd 67 4 cy
我希望它显示:
12 5 输入错误 67 4 输入错误
然而,它只给了我12,5,后面是输入错误,并停止了。 我尝试将所有内容放入while循环中,但它会无限循环出现输入异常。
public static void readNumbers()
 {

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
     try
     {
         Scanner reader = new Scanner(inputFile);
         while(reader.hasNext())
         {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            } 
      }
      catch (InputMismatchException e)
      {
                System.out.println("Input error ");
      }
      catch (FileNotFoundException e2)
      {
          System.out.println("File not found!");
      }    
  }

 }

我错过了什么,以便循环继续读取下一个整数等等?

2
try/catch 语句放在循环内部。 - SJuan76
@SJuan76 哎呀!你在我回答之前就评论了。我讨厌在stackoverflow上格式化代码块。 - Tom Heard
3个回答

5

尝试/捕获块需要在循环内部。

当异常被抛出时,控制权会一直向外传递,直到遇到一个捕获块为止,而在您的情况下,这个块是在循环外面。

public static void readNumbers()
{

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext())
        {
            try
            {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Input error ");
            }
        }
    }
    catch (FileNotFoundException e2)
    {
        System.out.println("File not found!");  
    }

}

我尝试将所有内容放入while循环中,但输入异常时它会无限循环。你提到你已经尝试过了。我需要更多关于你遇到的问题的细节,因为这是正确的方法。从我的直觉来看,可能是reader.nextInt()在异常发生时没有推进读取器在文件中的位置,因此再次调用nextInt会读取相同的非整数块。
也许您的catch块需要调用reader.getSomethingElse?例如reader.next()?
这只是一个想法,我还没有测试过:
public static void readNumbers()
{

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext())
        {
            try
            {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Input error ");
                reader.next();   // THIS LINE IS NEW
            }
        }
    }
    catch (FileNotFoundException e2)
    {
        System.out.println("File not found!");  
    }

}

[编辑 9:32 PM]

我的观点是让读者更易理解。

根据Scanner的Java文档:

将输入的下一个标记作为int进行扫描。如果下一个标记不能按以下描述转换为有效的int值,则此方法将抛出InputMismatchException。如果转换成功,则扫描器将超越与之匹配的输入。

http://docs.oracle.com/javase/7/docs/api/


FileNotFoundException出现在Scanner reader = new Scanner(inputFile);这一行,而不是reader.nextInt(),请修复。 - Tom Heard
好的观点。我不确定,所以决定保留它。 - Brandon
就是这样!我在某个地方看到过,尝试了一下,但可能放错了位置...谢谢!!!!!! - andcas7
有趣的是,我从未想过要检查扫描器是否在遇到InputMismatch时前进。对我来说,它似乎非常奇怪,但是嘿,肯定有原因。 - Tom Heard
实际上,现在我想更多地思考一下,那应该是正确的行为,因为一旦捕获InputMismatchException,您可能希望以其他某种方式读取该值。 - Tom Heard

2
在循环中放置try-catch,如下所示:
public static void readNumbers()
{
    File inputFile = new File ("C:/users/AC/Desktop/input.txt");

    try
    {  
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext())
        {
            try
            {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Input error ");
            }
        }
    }
    catch (FileNotFoundException e2)
    {
        System.out.println("File not found!");
    }  
}

编辑:请注意,此代码会导致循环在第一行引起InputMismatchException的地方无限循环。请参考接受的答案以修复此错误。


我已经尝试过了。但是我还是再试了一遍,但它会创建一个无限循环,并捕获@ InputMismatchException,不会继续执行下一个int或异常。 - andcas7
我看到你的回答了,我想我已经解决了你的无限循环问题。 - Brandon

1
当异常发生时,控制权转移到匹配的catch块,然后转移到该catch块之后的代码。在您的情况下,匹配的catch位于while循环外部,因此while循环被停止。将相应的catch块移动到while循环中。在您的代码中,reader.nextInt();是可能导致InputMismatchException的行。
        try {
            int num = reader.nextInt();
            System.out.println("Number read: " +num);
        } catch (InputMismatchException e) {
            System.out.println("Input error ");
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接