问题和练习的答案

Questions

try {
    
} finally {
   
}

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

catch (Exception e) {
     
}

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

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

try {

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

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

Answer:

Exercises

答案: 参见ListOfNumbers2.java.

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) {
            }
        }
    }
}
首页