package myPro1;
public class Person {
private int age;
//throws的作用,让调用setAge的处理异常
public void setAge(int age) throws Exception {
if (age < 0) {
Exception e = new Exception();
throw e;//如果年龄小于0,抛出异常
}
this.age = age;
}
}
package myPro1;
public class TestMain {
public static void main(String[] args) {
Person person=new Person();
try {
person.setAge(-11);
} catch (Exception e) {
System.out.println("年龄不能设为负数");
}
}
}