【发布时间】:2013-12-14 06:19:56
【问题描述】:
我正在学习 Java 中的功能,包括异常。我正在编写自定义异常。这是我正在做的事情:自定义异常类:
public class ServiceException extends Exception {
private String customMessage;
public ServiceException(String customMessage) {
super(customMessage);
this.customMessage = customMessage;
}
}
主类:
public class Main {
public static void main(String[] args) {
try {
new Main().test();
} catch (Exception e) {
System.out.println("the exception message is " + e.getMessage());
}
}
public void test() throws ServiceException {
try {
int i = 1 / 0;
} catch (Exception e) {
throw new ServiceException(e.getMessage());
}
}
}
我知道的就这么多: 如果自定义异常类中没有调用超类构造函数,则自定义异常中设置的消息不会传递给Exception类。但是,如果我的自定义异常类中有一个方法 public String getMessage ,即使没有调用超级,也会打印该消息。对不起,如果这是一个幼稚的问题。但我无法理解他的概念。有没有人可以帮助澄清这个概念?
【问题讨论】:
标签: java constructor superclass