易百教程

144、以下 Java 程序的输出是什么?

class Calculation extends Exception {

    public Calculation() {
        System.out.println("Calculation class is instantiated");
    }

    public void add(int a, int b) {
        System.out.println("The sum is " + (a + b));
    }
}

public class Main {

    public static void main(String[] args) {
        try {
            throw new Calculation();
        } catch (Calculation c) {
            c.add(10, 20);
        }
    }
}

运行结果:

Calculation class is instantiated
The sum is 30

解释Calculation 的对象是从 catch 块中捕获的 try 块中抛出的。 Calculation 类的 add() 使用该类的对象调用整数值 1020。 因此,总和 30 被打印出来。 Main类的对象只有在对象的类型是可抛出的情况下才能抛出。 为此,需要扩展 throwable 类。