哈喽,本章和大家一起学习异常抛出和类型自定义!
一、抛出异常
throw生成异常对象,一般和throws搭配使用
throws声明异常类型
二、自定义
先继承已知的异常类型,一般是Exception或RunTimeException
用surper引用父类的有参构造(String message)
例题:抛出“马化腾”异常
public class WrongNameException extends RuntimeException {
public WrongNameException(String message){
super(message);
}
}
public class Student {
private String name;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setName(String name) throws WrongNameException {
if (name.equals("马化腾")) {
throw new WrongNameException("姓名马化腾异常");
}
this.name = name;
}
public static void main(String[] args) {
Student s = new Student();
try {
s.setName("马化腾");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s.getName());
输出结果
null
cn.kgc.WrongNameException: 姓名马化腾异常
at cn.kgc.Student.setName(Student.java:28)
at cn.kgc.Student.main(Student.java:36)