如何显示我自己的 FileNotFoundException 消息

How to display my own FileNotFoundException message

我在 Java 中遇到自定义异常抛出问题。 具体来说,我想故意抛出 FileNotFoundException 以测试名为 fileExists() 的方法。该方法测试文件 (A) 是否不存在、(b) 不是普通文件或 (c) 不可读。它为每种情况打印不同的消息。 但是,当 运行 以下代码时,main 方法显示默认的 FileNotFoundException 消息,而不是 fileExists 方法中的一个。我很想听听关于原因的任何想法。 声明了所有变量,但我没有在此处包含所有声明。

public static void main (String[] args) throws Exception {
    try {

        inputFile = new File(INPUT_FILE);  // this file does not exist
        input = new Scanner(inputFile);
        exists = fileExists(inputFile);
        System.out.println("The file " + INPUT_FILE 
                + " exists. Testing continues below.");

    } catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }

}

public static boolean fileExists(File file) throws FileNotFoundException {
    boolean exists = false;    // return value
    String fileName = file.getName();  // for displaying file name as a String

    if ( !(file.exists())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " does not exist.");
    }

    else if ( !(file.isFile())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
    }

    else if ( !(file.canRead())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " is not readable.");
    }

    else {
        exists = true;
    }

        return exists;

}

首先,您可能希望避免使用与现有 Java class 相同的 class 名称,以避免混淆。

在您的 main 方法中,您需要在使用创建 Scanner 对象之前检查文件是否存在。

此外,不需要所有 exists = false 代码停止时抛出异常的地方。

可能的解决方案如下:

public static boolean fileExists(File file) throws FileNotFoundException {
    String fileName = file.getName();  // for displaying file name as a String

    if (!(file.exists())) {
        throw new FileNotFoundException("The file " + fileName + " does not exist.");
    }

    if (!(file.isFile())) {
        throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
    }

    if (!(file.canRead())) {
        throw new FileNotFoundException("The file " + fileName + " is not readable.");
    }

    return true;
}

public static void main(String[] args) throws Exception {
    String INPUT_FILE = "file.txt";

    try {
        File inputFile = new File(INPUT_FILE);

        if (fileExists(inputFile)) {
            Scanner input = new Scanner(inputFile);

            System.out.println("The file " + INPUT_FILE + " exists. Testing continues below.");
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
}

您也可以创建一个 class,其中扩展 FileNotFoundException 给它一个 File 作为参数,然后将它扔到您的 catch 中,然后继续覆盖您所说的 class 中的打印输出。