学习处理异常,无法弄清楚这个文件未找到异常



我还是初学者,目前正在学习如何处理异常。我试图弄清楚的书中的练习告诉我添加一个 Final 块来关闭我打开的文件,我不明白我做错了什么。请记住文件名和路径是假的,但这是我所拥有的:

public static String readLineWithFinally()
{
    System.out.println("Starting readLineWithFinally method.");
    RandomAccessFile in = new RandomAccessFile("products.ran", "r");
    try
    {                     
        String s = in.readLine();
        return s;
    } 
    catch (IOException e)
    {
        System.out.println(e.toString());
        return null;
    }
    finally
    {
        try
        {
                in.close();
        }
        catch (Exception e)
        {
            System.out.println("Generic Error Message");
        }
    }
}    

为了补充Taylor Hx的答案,你可以利用Java 7的try-with-resources结构来避免在你的情况下完全使用finally

public static String readLineWithFinally() {
    System.out.println("Starting readLineWithFinally method.");
    try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
        return in.readLine();
    } catch (IOException e) {
        System.out.println(e.toString());
        return null;
    }
}

您还需要确保您的使用情况与 API 对RandomAccessFile的要求一致。

您发布的代码不应该编译,因为 RandomFile(字符串,字符串(可能会抛出FileNotFoundException。因此,我们必须将其包含在try块中。

System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
try {
    in = new RandomAccessFile("products.ran", "r");
    String s = in.readLine();
    return s;
} catch (IOException e) {
    System.out.println(e.toString());
    return null;
} finally {
    try {
        if(in != null) {
            in.close();
        }
    } catch (Exception e) {
        System.out.println("Generic Error Message");
    }
}

请记住文件名和路径是假的,但这是我所拥有的:

这就是为什么您在创建具有读取访问模式RandomAccessFile("products.ran", "r")时会遇到FileNotFoundException "r" .

从文档中: RandomAccessFile(String name, String mode)

FileNotFoundException如果模式为 "r"但给定的字符串不表示现有的常规文件, 或者如果模式以"rw"开头,但给定的字符串不表示 现有的可写常规文件和该名称的新常规文件 无法创建,或者在打开或 创建文件

最新更新