Person类代码:
package com.bdqn; public class Person { private int age; public int getAge() { return age; } public void setAge(int age) throws Exception{ if(age>=1 && age<=100){ this.age = age; }else{ throw new Exception("年龄必须在1—100之间!"); } } }
测试类代码:
package com.bdqn; public class TestAge { public static void main(String[] args) { Person person = new Person(); try{ person.setAge(1231312); }catch (Exception e){ e.printStackTrace(); } } }
运行结果: