【问题标题】:Unhandled Exception Type IOException [duplicate]未处理的异常类型 IOException [重复]
【发布时间】:2023-03-12 18:49:01
【问题描述】:

可能重复:
Why do I get the “Unhandled exception type IOException”?

我正在尝试使用以下算法求解 Euler #8。问题是,每当我修改有巨大注释的行时,错误Unhandled Exception Type IOException 就会出现在我用注释//### 标记的每一行上。

private static void euler8()
{   
    int c =0;
    int b;
    ArrayList<Integer> bar = new ArrayList<Integer>(0);
    File infile = new File("euler8.txt");
    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(
                            new FileInputStream(infile), //###
                            Charset.forName("UTF-8")));
        while((c = reader.read()) != -1) { //###
          char character = (char) c;
          b = (int)character;
          bar.add(b); /*When I add this line*/
        }
    reader.close(); //###
}

【问题讨论】:

  • 阅读Exceptions Tutorial,然后使用该知识将代码包装在 try/catch 中或抛出异常——您的选择。

标签: java file-io io ioexception


【解决方案1】:

是的,IOException 是一个已检查异常,这意味着您要么需要捕获它,要么声明您的方法也会抛出它。如果抛出异常,您希望发生什么?

请注意,您通常应该在 finally 块中关闭 reader,这样即使遇到另一个异常,它也会关闭。

有关已检查和未检查异常的更多详细信息,请参阅Java Tutorial lesson on exceptions

【讨论】:

  • 我在方法签名中添加了 throws,但是如果我不包含 try{},我将如何包含 finally 块?
  • @JamesRoberts - 您可以使用try/finally 结构(没有任何catch 块)。如果您使用的是 Java 7,另一种方法是使用 try-with-resources 语句。
  • 此外,我不再在方法中遇到错误,但是方法调用中有 Unhandled Exception Type IOException 错误。
  • @JamesRoberts - 在调用层次结构的某个级别,您需要处理代码可能出现的异常。这一切都回到了 Jon 的问题:如果出现异常(例如,如果文件无法打开),您希望发生什么?
  • @James:请阅读本教程,因为它会解释所有内容,并且比尝试使用工具而不首先了解它们要好。
【解决方案2】:

一种解决方案:改为

private static void euler8() throws IOException {

但是调用方法必须捕获 IOException。

或捕获异常:

private static void euler8()
{   
    int c =0;
    int b;
    ArrayList<Integer> bar = new ArrayList<Integer>(0);
    BufferedReader reader;
    try { 
        File inFile = new File("euler8.txt");
        reader = new BufferedReader(
                            new InputStreamReader(
                            new FileInputStream(infile), //###
                            Charset.forName("UTF-8")));
        while((c = reader.read()) != -1) { //###
          char character = (char) c;
          b = (int)character;
          bar.add(b); /*When I add this line*/
        }
    } catch (IOException ex) {
       // LOG or output exception
       System.out.println(ex);
    } finally {
        try {
           reader.close(); //###
        } catch (IOException ignored) {}
    }
}

【讨论】:

    【解决方案3】:

    包装在 try/catch 块中以捕获异常。

    如果您不这样做,它将无法处理。

    【讨论】:

      【解决方案4】:

      如果您无法读取指定文件会怎样? FileInputStream 将引发异常,Java 要求您必须检查并处理它。

      这种类型的异常称为已检查异常。 未经检查的异常存在,Java 不需要您处理这些(主要是因为它们无法处理 - 例如OutOfMemoryException

      请注意,您的处理可能包括捕捉和忽略它。这不是一个好主意,但 Java 无法真正确定 :-)

      【讨论】:

        猜你喜欢
        • 2021-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2016-07-04
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        相关资源
        最近更新 更多