1、设计一个Person类,该类包含一个age属性,即人的年龄,该值不能为负数;
2、在给该对象属性赋值为负数时,抛出异常,有两种方式可以实现;
2.1、在Person对象的setAge方法中将异常进行抛出,uncheked方式,能正常编译通过,运行时报错;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| public class Person{
private int age;
public void setAge(int age){
if (age < 0){
throw new RuntimeException("年龄不能为负数...");
}
this.age = age;
}
}
class Demo{
public static void main(String args[]){
Person p = new Person();
p.setAge(-1);
}
}
运行结果:
Exception in thread "main" java.lang.RuntimeException: 年龄不能为负数...
at Person.setAge(Person.java:5)
at Demo.main(Demo.java:4) |
public class Person{
private int age;
public void setAge(int age){
if (age < 0){
throw new RuntimeException("年龄不能为负数...");
}
this.age = age;
}
}
class Demo{
public static void main(String args[]){
Person p = new Person();
p.setAge(-1);
}
}
运行结果:
Exception in thread "main" java.lang.RuntimeException: 年龄不能为负数...
at Person.setAge(Person.java:5)
at Demo.main(Demo.java:4)
[……]
继续阅读