代码之家  ›  专栏  ›  技术社区  ›  Henrik

在FileWriter上使用try catch

  •  1
  • Henrik  · 技术社区  · 7 年前

    我有一个关于FileNotFoundException的问题。我得到的接口定义了方法名,包括“throws filenotfoundexcution”。

    public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
    
        try {
            FileWriter writer = new FileWriter(filename);
            for (String str : assignment) {
                writer.write(str + "\n");
            }
            writer.close();
    
        } catch (IOException e) {
            System.err.print("Something went wrong");
        }
    }
    

    2 回复  |  直到 7 年前
        1
  •  3
  •   JMax    7 年前

    IOException 是一个超级类 FileNotFoundException . 因此,你的拦截 IO异常 还捕捉到每个 FileNotFoundException

    您应该实现以下功能:

    public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
    
        try (FileWriter writer = new FileWriter(filename)) {
            for (String str : assignment) {
                writer.write(str + "\n");
            }
        } catch (FileNotFoundException e) {
            throw e; // catch and re-throw
        } catch (IOException e) {
            System.err.print("Something went wrong");
        }
    }
    
        2
  •  0
  •   Zenith    7 年前

    您可以捕获异常而不是IOException

    public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {
    
    try {
        FileWriter writer = new FileWriter(filename);
        for (String str : assignment) {
            writer.write(str + "\n");
        }
        writer.close();
    
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
    

    通过这种类型编码,您可以查看/学习异常的层次结构。 如果您想在是否捕获异常的情况下执行程序,可以使用 块在那里你将关闭你的作家。