请告诉我,异常的描述没有出现

时间:2011-06-13 09:59:03

标签: java exception-handling

package javaapplication16;

class ExceptionoftheGods extends Exception {

    double b;

    ExceptionoftheGods (String msg){
    }

}

class mak {

    static void compute(int a) throws ExceptionoftheGods {
        System.out.println("Called Compute(" + a + ")");
        if(a > 7) {
            throw new ExceptionoftheGods("Dog");
        }
        System.out.println("Normal Exit");
    }    


    public static void main(String[] args) {
        try {
            compute(1);
            compute(9);
        } catch(ExceptionoftheGods e) {
            System.out.println(" Caught " + e);
        }
    }

}

输出

run:
Called Compute(1)
Normal Exit
Called Compute(9)
 Caught javaapplication16.ExceptionoftheGods
BUILD SUCCESSFUL (total time: 0 seconds)

3 个答案:

答案 0 :(得分:5)

ExceptionoftheGods(String msg) {
    super(msg); // missing
}

答案 1 :(得分:1)

您需要在子类的构造函数中调用基本异常构造函数,否则实际上不会设置消息:

ExceptionoftheGods(String msg) {
    super(msg);
}

此外,您正在打印异常对象本身,而不是异常的消息。如果您只想打印需要直接调用getMessage()的消息,否则您将获得异常的类型和描述。

更改

System.out.println(" Caught " + e);

System.out.println(" Caught " + e.getMessage());

答案 2 :(得分:0)

定义新方法时,必须定义其所有功能。如果您希望它作为父类方法工作,则必须调用super

要么您没有定义构造函数(并且只保留默认的-empty-构造函数),要么修改构造函数。

ExceptionoftheGods (String msg){
  super(msg);
}