package unit5; public class Person { private int age; private String name; public String getName() { return name; } public int getAge() { return age; } public void setAge(int a) throws Exception { if(a<0){ throw new Exception("出现异常,年龄不能小于零"); } if(a>1000){ throw new Exception("出现异常,年龄不能大于1000"); } age = a; } public void setName(String name) { this.name=name; } public void display() { System.out.println("我叫 "+name+"今年 "+age+" 岁。"); } }
package unit5; public class Throwsdeml { public static void main(String[] args) { Person zhang = new Person(); try{ zhang.setName("张三"); zhang.setAge(2000); zhang.display(); }catch (Exception e) { System.out.println(e.getMessage()); } } }
时间: 2024-10-29 19:05:49