问题和练习的答案

Questions

  • 问题: 以下代码是否合法?
try {
    
} finally {
   
}

答案: 是的,这是合法的,并且非常有用如果try语句具有finally块,则不必具有catch块。如果try语句中的代码具有多个 Export 点并且没有关联的catch子句,则无论try块如何退出,都将执行finally块中的代码。因此,只要有必须始终执行的代码,就提供finally块是有意义的。这包括资源恢复代码,例如关闭 I/O 流的代码。

  • 问题: 以下处理程序可以catch哪些异常类型?
catch (Exception e) {
     
}

使用这种类型的异常处理程序有什么问题?

答案: 此处理程序catchException类型的异常;因此,它catch任何异常。这可能是一个较差的实现,因为您将丢失有关引发的异常类型的有价值的信息,并使您的代码效率降低。因此,在决定最佳恢复策略之前,您的程序可能不得不确定异常的类型。

  • 问题: 编写的此异常处理程序有什么问题吗?这段代码可以编译吗?
try {

} catch (Exception e) {
   
} catch (ArithmeticException a) {
    
}

答案: 这个第一个处理程序catchException类型的异常;因此,它将catch任何异常,包括ArithmeticException。永远无法到达第二个处理程序。此代码将无法编译。

  • 问题: 将第一个列表中的每种情况与第二个列表中的项目进行匹配。

  • int[] A; A[0] = 0;

    • JVM 开始运行您的程序,但是 JVM 找不到 Java 平台类。 (Java 平台类位于classes.ziprt.jar中.)

    • 程序正在读取流并到达end of stream标记。

    • 在关闭流之前和到达end of stream标记之后,程序将try再次读取流。

  • __error

    • __checked exception

    • __compile error

    • __no exception

Answer:

  • 3 (编译错误)。数组未初始化,将无法编译。

    • 1 (error).

    • 4 (也不 exception)。读取流时,您希望流标记结束。您应该使用异常来catch程序中的意外行为。

    • 2 (已检查的异常)。

Exercises

  • 锻炼:ListOfNumbers.java添加readList方法。此方法应从文件中读取int个值,打印每个值,并将它们附加到向量的末尾。您应该catch所有适当的错误。您还需要一个包含数字的文本文件才能读入。

答案: 参见ListOfNumbers2.java.

  • 锻炼: 修改以下cat方法,使其可以编译:
public static void cat(File file) {
    RandomAccessFile input = null;
    String line = null;

    try {
        input = new RandomAccessFile(file, "r");
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        return;
    } finally {
        if (input != null) {
            input.close();
        }
    }
}

答案: catch异常的代码以粗体显示:

public static void cat(File file) {
    RandomAccessFile input = null;
    String line = null;

    try {
        input = new RandomAccessFile(file, "r");
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        return;
    } catch(FileNotFoundException fnf) {
        System.err.format("File: %s not found%n", file);
    } catch(IOException e) {
        System.err.println(e.toString());
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch(IOException io) {
            }
        }
    }
}