捕获异常并请求用户重新输入

人气:379 发布:2022-10-16 标签: java exception java.util.scanner

问题描述

我正在创建一个打开然后读取用户指定的文件的程序,目前我拥有的代码如下所示:

    System.out.println("Enter the name of the file you want to open: ");
    FileN = scan.nextLine();
    // I want the program to return to this point here if an error has occured.
    try
    {
        scan = new Scanner(new File (FileN));
    }
    catch(Exception e)
    {
        System.out.println("Could not find file" + e);
        System.out.println("Please enter a valid file name: ");

    }
我已经在上面指定了我希望程序在代码中返回的位置,我目前已经尝试创建一个循环,然后使用Continue,但是它不会让我在循环中尝试。此外,我试图创造一个新的空白,但它仍然不起作用。当前,即使用户输入了无效的文件名,程序也会继续运行。

我已经搜索了答案,但只能找到与我想要的内容相关的答案:Java - Exception handling - How to re-enter invalid input

还澄清了在循环中尝试是什么意思;是的,这是可能的。但是,我想知道为了继续在我的程序中工作,我是将try放入循环中,还是将循环放入try中?我已经提到:Should try...catch go inside or outside a loop?

This is the error I'm currently getting with my latest code

推荐答案

如果您使用Exception,从它的本意是用来处理意想不到的事情的意义上来说,它会变得更容易一些。正如预期的那样,不存在的文件并不是真正的例外。存在但无法打开的文件,或者正在打开但内容为零的文件(即使它有1MB的内容)是意想不到的事情,因此也是例外。考虑到不存在的文件的预期行为(因为它是由用户键入的,而用户可能键入不正确),您可以使用如下内容:

boolean fileExists = false;
File newFile;
while(!fileExists) {
  System.out.println("Enter the name of the file you want to open: ");
  FileN = scan.nextLine();
  newFile = new File(FileN);
  fileExists = newFile.exists();
  if (!fileExists) {
    System.out.println(FileN + " not found...");
  }
}
try {
    Scanner scan;
    scan = new Scanner(newFile);
    ... do stuff with the scanner
}
catch(FileNotFoundException fnfe) {
  System.out.println("sorry but the file doesn't seem to exist");
}

941