* 自定义异常:如果JDK中异常类型无法满足程序需要。
* 步骤:
* 1.编写自定义异常类:继承Exception或RuntimeException
* 2.编写构造方法,继承父类的实现
* 3.实例化自定义异常对象
* 4.使用throw抛出
例:
public class SexException extends Exception{
public SexException(String message){
super(message);
}
}
public class TestSexException {
public static void main(String[] args) {
Student student = new Student();
student.setName("张三");
try {
student.setAge(200);
student.setSex("男");
} catch (SexException e) {
// e.printStackTrace();
System.err.println(e.getMessage());
}catch(AgeException e){
System.err.println(e.getMessage());
}finally{
System.out.println("设置完成!");
}
System.out.println(student);
}
}
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>=1&&age<=100){
this.age = age;
}else{
throw new AgeException("年龄必须在1~100之间!");
}
}
public String getSex() {
return sex;
}
public void setSex(String sex) throws SexException{
if(sex.equals("男")||sex.equals("女")){
this.sex = sex;
}else{
throw new SexException("性别必须为男或女");
}
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}