throw和throws的使用 public class Person { private String name; private int age; public Person(){ } Person(String name,int age){ this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setAge(int age) throws Exception{ if (age<1||age>120){ throw new Exception("年龄错误,必须在1-120岁之间:"+age); }else { this.age = age; } } @Override public String toString() { return "Person{name="+name+",age"+age+"}"; } public static void main(String[] args) { Person person = new Person(); person.setName("张三"); try { person.setAge(340); }catch (Exception e){ e.printStackTrace(); } System.out.println(person); } }