Given the code fragment:

class X {
    public void printFileContent() {
        /* code goes here */
        throw new IOException();
    }
}
public class Test {
    public static void main(String[] args) {
        X xobj = new X();
        xobj.printFileContent();
    }
}

Which two modifications should you make so that the code compiles successfully?

A. Replace line 8 with:

public static void main(String[] args) throws Exception {

B. Replace line 10 with:

try {
    xobj.printFileContent();
} catch (Exception e) {
} catch (IOException e) {
}
C. Replace line 2 with:
public void printFileContent() throws IOException {
D. Replace line 4 with:
throw IOException("Exception raised");
E. At line 11, insert
throw new IOException();

题解

第 4 行在 X 类别的「printFileContent」方法中抛出了新的「IOException」例外,IOException 是需要检查的例外(checked exception),因此必须要撰写程序去处理它。

由于「printFileContent」方法中目前并没有任何处理「IOException」的方式,因此可以利用选项 C,将「printFileContent」方法中所产生的「IOException」往外抛出。选项 D 缺少了「new」操作符来实体化出 IOException 对象,但就算有「new」操作符也无济于事。

将「IOException」从「printFileContent」方法抛出后,其它有使用到「printFileContent」方法的地方就必须要去处理这个「IOException」,因此可以利用选项 A,继续将「IOException」再从「main」方法往外抛出。选项 B 的 try-catch 用法是错的,若把「Exception」和「IOException」调换,或是移除掉其中一组 catch,才会是正确的。

选项 E 虽然可以加至程序中,但无济于事。