/**
* 测试类
*/
class k5{
Scanner scanner = new Scanner(System.in);
public void show(){
try {
Person p1 =new Person();
//进行添加测试
p1.setAge(101);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("添加完成");
}
}
class Person{
public Person() {
}
public Person(String name, int age, char xingbie) {
this.name = name;
this.age = age;
this.xingbie = xingbie;
}
private String name;
private int age;
private char xingbie;
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("年龄异常!");
}
}
public char getXingbie() {
return xingbie;
}
public void setXingbie(char xingbie) {
this.xingbie = xingbie;
}
}
/**
* 自定义异常类
* 继承Exception类
* 实现定义异常类的构造方法
*/
class AgeException extends Exception{
public AgeException(String message) {
super(message);
}
}
/**
* 自定义异常类二
* 继承RunTimeException类(区别在于继承RunTimeException
* 在代码中抛出异常后方法体不需要再抛出异常,因为继承的类就是运行时异常类,用于抛运行时异常,这个类比较特殊)
* 实现定义异常类的构造方法
*/
class AgeException2 extends RunTimeException{
public AgeException(String message) {
super(message);
}
}
自定义异常及其使用
于 2022-04-25 09:42:53 首次发布