我正在阅读文档 here 。这个例子就是我所质疑的:
The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
在 PHP 中,我会在接受文件作为有效的用户输入之前检查该文件是否存在,例如:
if (file_exists($file)) {
//proceed
} else {
//throw error to user
}
通过阅读这篇文章,我是否可以理解,在 Java 中,您只需要“假设”提供的文件是有效的,并使用异常处理程序抛出错误,而不是仅仅检查它是否存在?或者使用异常是一种更干净/有效的检查文件是否存在的方法?
最佳答案
两种方法都可以;这更有意义取决于上下文——但是无论它是如何实现的,检查的异常必须要么被处理,要么被声明为抛出。这可能会改变最有意义的东西。
我倾向于在尝试对文件执行任何操作之前检查文件是否存在。但异常(exception)只是——(通常)用于特殊情况。
例如,我的应用程序检查该文件是否存在,并且确实存在。从那时起到使用该文件之间,会出现其他东西并将其删除。现在有一个特殊情况,我的代码必须尽可能优雅地处理。
关于java - 有效的 Java 异常处理 - 是否在所有情况下都需要它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8395243/