java自定义异常
/**
* 自定义异常
*/
public class Test05 {
}
class IllegalAgeException extends Exception{
//非法年龄异常类 继承异常类
public IllegalAgeException(){}
//无参构造器
public IllegalAgeException(String message){
//message中放异常的信息/描述
super(message);
//调用父类的有参构造器 构造器不能继承 不写时默认第一行super()调用无参构造器
}
}
class IllegalNameException extends Exception{
public IllegalNameException(){}
public IllegalNameException(String message){
super(message);
}
}
class Adult{
String name;
int age;
public void setAge(int age){
if (age<19){
try {
throw new IllegalAgeException("年龄需满18周岁");
//对数值进行限制 当这里抛出新的异常对象时 checked exception提示将这个异常进行try/catch处理或者Add exception to method signature 向方法签名添加异常
} catch (IllegalAgeException e) {
//try尝试抛出 new IllegalAgeException catch这个new的exception用IllegalAgeException引用变量e指向 并且执行{抛出new运行时异常}
throw new RuntimeException(e);
}
}
this.age = age;
}
public void setName(String str) throws IllegalNameException{
//对方法内的new异常 通过throws抛出
if (str==""){
throw new IllegalNameException("需要输入有效字符");
}
name = str;
}
public static void main(String[] args) {
Adult a = new Adult();
a.setAge(-1);
/*
Exception in thread "main" java.lang.RuntimeException: IllegalAgeException: 年龄需满18周岁
at Adult.setAge(Test05.java:27)
at Adult.main(Test05.java:35)
Caused by: IllegalAgeException: 年龄需满18周岁
at Adult.setAge(Test05.java:24)
... 1 more
Process finished with exit code 1
程序通过了编译 但在运行(Test05.java:35行)时throw异常 属于运行时异常 : 冒号后是异常的信息 在setAge()方法内抛出的IllegalAge异常已被catch处理 但(Test05.java:27行)new Runtime异常叫停了进程
throw new RuntimeException(e); 将IllegalAge异常对象e传参进 RuntimeException()构造方法中
new Runtime异常的原因Caused by IllegalAge异常: 异常的信息
在(Test05.java:24行) throw new IllegalAgeException("年龄需满18周岁");
*/
try {
a.setName("");
//checked exception提示处理非法命名异常
} catch (IllegalNameException e) {
e.printStackTrace();
//打印栈跟踪信息
System.exit(-1);
//系统退出返回-1异常退出
}
/*
IllegalNameException: 需要输入有效字符
at Adult.setName(Test05.java:43)
at Adult.main(Test05.java:66)
Process finished with exit code -1
异常类:信息
(Test05.java:43) throw new IllegalNameException("需要输入有效字符");
(Test05.java:66) a.setName("");
这里的异常退出是手动在catch{}语句块中添加的 没有这一项的话进程会在catch异常后继续往下运行至结束
*/
}
}