java自定义一个学生类,属性有 姓名 年龄,如果用户在给学生年龄赋值时,年龄小于0抛出一个AgeLT0Exception,大于150 抛出一个AgeGT150Exception

自定义一个学生类,属性有 姓名 年龄,如果用户在给学生年龄赋值时,年龄小于0抛出一个AgeLT0Exception,大于150 抛出一个AgeGT150Exception
1.写Test类
Class Test

	public static void main(String[] args) throws AgeGT150Exception, AgeLT0Exception {
		Student s = new Student();
			s.setAge(50);
			System.out.println(s.toString());
	}

2.写AgeGT150Exception类继承Exception (大于150)
Class AgeGT150Exception

public class AgeGT150Exception extends Exception{

	public AgeGT150Exception() {
		super();
		// TODO Auto-generated constructor stub
	}

	public AgeGT150Exception(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

}

3.写 AgeLT0Exception类继承Exception(小于0)
Class AgeLT0Exceptionn

public class AgeLT0Exception extends Exception{
	public AgeLT0Exception() {
		super();
		// TODO Auto-generated constructor stub
	}

	public AgeLT0Exception(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}
}

4.写Student类
Class Student

public class Student {
	String name = "艾力";
	int age;
	public int getAge() {
		return age;
	}
	public void setAge(int age) throws AgeGT150Exception, AgeLT0Exception {
		if(age>150) {
			throw new AgeGT150Exception("年龄超过150!");
		}
		if(age<0) {
			throw new AgeLT0Exception("年龄小于0!");
		}
			this.age = age;
	}
	@Override
	public String toString() {
		return "Student [姓名=" + name + ", 年龄=" + age + "]";
	}
}

age赋值50时输出的结果:

Student [姓名=艾力, 年龄=50]

age赋值200时输出的结果:

Exception in thread "main" Day17HomeWork.AgeGT150Exception: 年龄超过150!
	at Day17HomeWork.Student.setAge(Student.java:11)
	at Day17HomeWork.Test.main(Test.java:6)

age赋值-50时输出的结果:

Exception in thread "main" Day17HomeWork.AgeLT0Exception: 年龄小于0!
	at Day17HomeWork.Student.setAge(Student.java:14)
	at Day17HomeWork.Test.main(Test.java:6)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值