【问题标题】:Why does the Formatter(String fileName) constructor not work without handling FileNotFoundException? [duplicate]为什么 Formatter(String fileName) 构造函数在不处理 FileNotFoundException 的情况下不起作用? [复制]
【发布时间】:2018-05-17 14:40:41
【问题描述】:

即使文件已经存在,当我不处理 FileNotFoundException 时,构造函数 Formatter(String fileName) 似乎也无法编译。

这是有效的代码:

import java.util.*;

public class CreatingFiles {

public static void main(String[] args) {
    final Formatter MYFILE;

    try {
        MYFILE = new Formatter("john.txt");
        System.out.println("File created");
    }

    catch (Exception e) {
        System.out.println("Error!");
    }
  }
}

但是,当我删除 try/catch 块时:

import java.util.*;

public class CreatingFiles {

public static void main(String[] args) {
    final Formatter MYFILE;

    MYFILE = new Formatter("john.txt");
  }
}

编译器告诉我必须抛出或捕获异常。那么为什么不处理异常就不能工作呢?

【问题讨论】:

  • 编译器不知道文件是否存在。所以你总是需要处理异常
  • dd 向主方法声明抛出异常
  • 了解检查异常。

标签: java


【解决方案1】:

构造函数 Formatter(String) [https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)],抛出 FileNotFound 异常 [https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html]已检查异常 [@987654323 @,所以你必须抓住它或重新抛出它。

【讨论】:

    【解决方案2】:

    https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)

    SecurityException - 如果存在安全管理器并且 checkWrite(fileName) 拒绝对文件的写入访问权限

    FileNotFoundException - 如果给定的文件名不表示现有的可写常规文件并且无法创建具有该名称的新常规文件,或者在打开或创建文件时出现其他错误

    编译器不知道文件是否存在。它只会在执行时找到。

    你可以把throws ExceptionName放在方法声明中

    public void MyMethod() throws ExceptionName{
        //TODO
    }
    

    但是会被抛出给这个方法的调用者。

    【讨论】:

      【解决方案3】:

      FileNotFoundException 是已检查异常,这意味着您必须能够从中恢复,即。 e.显示类似The file could not be opened 的消息。用户经常删除文件,因此您无法确定您请求的文件确实存在。但是,如果您的应用程序仅因文件不存在而崩溃,这对用户来说将是非常糟糕的体验。

      因此,编译器会强制您处理您请求的文件不存在的情况。最有可能的是,您应该只向用户显示某种错误消息并记录异常。

      我发现this explanation of checked exceptions 在您有其他问题时非常有用。

      【讨论】:

      • 另外,如果对您有帮助,请考虑将我的回答标记为解决方案。
      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 2015-11-02
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多