自定义异常
系统异常不能满足需要
语法:1、继承Throwable 2、继承Exception 3.继承RuntimeException
package com.test;
public class People {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) throws Exception {
if("男".equals(gender) || "女".equals(gender)){
this.gender = gender;
} else{
throw new Exception("性别必须为男或者女!");
}
}
}
package com.test; public class TestException { public static void main(String[] args) { People p = new People(); try { p.setGender("male"); } catch (GenderException e) { System.out.println("性别设置出错!"); e.printStackTrace(); } } }
package com.test; /** * * 自定义异常类型 */ public class GenderException extends Exception { public GenderException(String msg){ super(msg); } }