【发布时间】:2019-11-12 02:22:46
【问题描述】:
在自定义异常类中我们调用超类(Exception class)的构造函数。为什么不直接调用Exception类构造函数而不是自定义类构造函数呢?请在下面找到示例
class InvalidAgeException extends Exception {
InvalidAgeException(String s) {
super(s);
}
}
class TestCustomException1 {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("not valid");
}
else {
System.out.println("welcome to vote");
}
}
public static void main(String args[]){
try {
validate(13);
}
catch (Exception m) {
System.out.println("Exception occured: " + m);
}
System.out.println("rest of the code...");
}
}
在上面的例子中我们可以使用 throw new Exception("not valid"); 那么这里自定义异常类有什么用呢?
【问题讨论】:
-
使用
throw new Exception("not valid");- 在阅读日志时您怎么知道它应该是InvalidAgeException?