自定义异常
/*
* 自定义异常
* 在实际开发中,有时候需要些自定义异常,也就是Exception体系中没有的异常,来解决一些特殊的问题?
* 如何创建自定义异常?
* 1:创建一个类继承Exception或者RuntimeException
* 1.1:继承Exception会让我们的异常类变为编译时异常
* 1.2:继承RuntimeException会让我们的异常类变为运行时时异常
* 2:提供无参和有参的构造器
* 如何使用自定义异常?
*/
public class Test {
public static void main(String[] args) {
//1:创建学生对象
Student stu = new Student();
//2:初始化学生
stu.setName("宝强");
try {
stu.setAge(2000);
} catch (AgeException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
stu.setSex("人妖");
} catch (SexException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public class Student {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if(age>=18 && age<=30){
this.age = age;
}else{
//System.out.println("年龄不符合范围 18~30");
//throw new Exception("年龄不符合范围 18~30");
throw new AgeException("年龄不符合范围 18~30");
}
}
public String getSex() {
return sex;
}
public void setSex(String sex) throws SexException{
if("女".equals(sex)||"男".equals(sex)){
this.sex = sex;
}else{
throw new SexException("性别只能是 男 or 女");
//throw new Exception("性别只能是 男 or 女");
//System.out.println("性别只能是 男 or 女");
}
}
public Student(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Student() {
super();
}
}
public class SexException extends RuntimeException {
public SexException(){
super();
}
public SexException(String message){
super(message);
}
}
public class AgeException extends Exception {
public AgeException(String message){
super(message);
}
public AgeException(){
super();
}
}