自定义一个异常,在这个异常中声明了一个属性age,一个方法getOverAge
public class OverageException extends Exception{
private int age;
public OverageException(int age) {
super();
this.age = age;
}
public int getOverAge(){
return age;
}
}
一个User类
public class User {
private String name;
private int age;
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public User() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age){
this.age = age;
}
User类中含有一个show方法,在其中进行age值的判断
public void show() throws OverageException{
if(this.age>=0&&this.age<=120)
{
System.out.println("姓名:"+this.name);
System.out.println("年龄:"+this.age);
return;
}
System.out.println("年龄须在0至120之间");
throw new OverageException(age);
}
测试类
public class Demo_Age {
public static void main(String[] args){
User us = new User("lili",130);
try {
us.show();
} catch (OverageException e) {
System.out.println("年龄是:"+e.getOverAge());
e.printStackTrace();
}finally{
System.out.println("程序结束");
}
}
}
测试结果