如何循环一个try catch语句? [英] How to loop a try catch statement?

查看:488
本文介绍了如何循环一个try catch语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何循环执行try/catch语句?我正在编写一个使用扫描仪读取文件并从键盘读取文件的程序.所以我要的是如果文件不存在,程序将显示此文件不存在,请重试."然后让用户输入其他文件名.我尝试了几种不同的方法来尝试执行此操作,但是所有尝试最终都导致程序崩溃.

How do you loop a try/catch statement? I'm making a program that is reading in a file using a Scanner and it's reading it from the keyboard. So what I want is if the file does not exist, the program will say "This file does not exist please try again." then have the user type in a different file name. I have tried a couple different ways to try an do this but, all of my attempts end up with the program crashing.

这就是我所拥有的

    try {
        System.out.println("Please enter the name of the file: ");
        Scanner in = new Scanner(System.in);
        File file = new File(in.next());
        Scanner scan =  new Scanner(file);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("File does not exist please try again. ");
    }

推荐答案

如果您想在失败后重试,则需要将该代码放入循环中;例如像这样的东西:

If you want to retry after a failure, you need to put that code inside a loop; e.g. something like this:

boolean done = false;
while (!done) {
    try {
        ...
        done = true;
    } catch (...) {
    }
}

(做一会儿"是一种稍微优雅的解决方案.)

(A do-while is a slightly more elegant solution.)

但是,在这种情况下赶上Exception是错误的做法.它不仅可以捕获您预期会发生的异常(例如IOException),而且还可以捕获意外的异常(例如NullPointerException等),这些异常是程序中错误的症状.

However, it is BAD PRACTICE to catch Exception in this context. It will catch not only the exceptions that you are expecting to happen (e.g. IOException), but also unexpected ones, like NullPointerException and so on that are symptoms of a bug in your program.

最佳实践是捕获您期望的(可以处理的)异常,并允许其他任何异常传播.在您的特定情况下,捕获FileNotFoundException就足够了. (这是Scanner(File)构造函数声明的内容.)如果您未在输入中使用Scanner,则可能需要捕获IOException.

Best practice is to catch the exceptions that you are expecting (and can handle), and allow any others to propagate. In your particular case, catching FileNotFoundException is sufficient. (That is what the Scanner(File) constructor declares.) If you weren't using a Scanner for your input, you might need to catch IOException instead.

我必须纠正最受好评的答案中的一个严重错误.

I must correct a serious mistake in the top-voted answer.

do {
    ....
} while (!file.exists());

这是不正确的,因为测试文件是否存在还不够:

This is incorrect because testing that the file exists is not sufficient:

  • 该文件可能存在,但用户无权读取它,
  • 该文件可能存在,但可以是目录,
  • 该文件可能存在,但由于硬盘错误或类似原因而无法打开
  • 在成功进行exists()测试与随后的尝试打开文件之间,可能会删除/取消链接/重命名该文件.
  • the file might exist but the user doesn't have permission to read it,
  • the file might exist but be a directory,
  • the file might exist but be unopenable due to hard disc error, or similar
  • the file might be deleted/unlinked/renamed between the exists() test succeeding and the subsequent attempt to open it.

请注意:

  1. File.exists()仅测试文件系统对象是否具有指定的路径,而不是它实际上是文件,还是用户具有对该文件的读取或写入访问权限.
  2. 由于硬盘错误,网络驱动器错误等,无法测试I/O操作是否失败.
  3. 对于打开vs删除/未链接/重命名竞争条件没有解决方案.尽管通常使用的情况很少见,但如果所讨论的文件对安全性至关重要,则可以将这种错误定位为.
  1. File.exists() ONLY tests that a file system object exists with the specified path, not that it is actually a file, or that the user has read or write access to it.
  2. There is no way to test if an I/O operation is going to fail due to an hard disc errors, network drive errors and so on.
  3. There is no solution to the open vs deleted/unlinked/renamed race condition. While it is rare in normal usage, this kind of bug can be targeted if the file in question is security critical.

正确的方法是简单地尝试打开文件,并在IOException发生时捕获并处理.它更简单,更强大,甚至可能更快.对于那些会说不应将异常用于常规流控制"的人来说,这不是常规流控制...

The correct approach is to simply attempt to open the file, and catch and handle the IOException if it happens. It is simpler and more robust, and probably faster. And for those who would say that exceptions should not be used for "normal flow control", this isn't normal flow control ...

这篇关于如何循环一个try catch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆