java - 有效的 Java 异常处理 - 是否在所有情况下都需要它?

标签 java

我正在阅读文档 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/

相关文章:

java - 如何在 Windows 和 Java 11 上调试 "Software caused connection abort: recv failed"?

java - 我们如何模拟 Ctrl+C 来阻止控制台应用程序等待 java 中的用户输入

java - 如何在我的JavaFX应用程序中进行劳累

java - 如何在开发过程中在一个地方捕获来自不同线程的所有未捕获异常?

java - 无法使用 Apache Tomcat 服务器访问硬盘驱动器中的文件

java堆大小增加

java - 正则表达式 + Java : split a text into words and removing punctuation only if they are alone or at the end

来自 XSLT 的 Java 代码生成器

java - 如何更改 Gradle 中的 jar 输出目录?

java - JAXB XmlElement 注释从 String 转换为 int