Person.java 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package J20250718.demo02_exception;
  2. /**
  3. * @author WanJl
  4. * @version 1.0
  5. * @title Person
  6. * @description
  7. * @create 2025/7/18
  8. */
  9. public class Person {
  10. private String name;
  11. private Integer age;
  12. private String sex; //性别
  13. private double height; //身高
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) throws NameSizeException{
  18. if (name==null){
  19. throw new NullPointerException();//空指针异常
  20. }
  21. if (name.length()<=0||name.length()>15){
  22. throw new NameSizeException();
  23. }
  24. this.name = name;
  25. }
  26. public Integer getAge() {
  27. return age;
  28. }
  29. public void setAge(Integer age) throws AgeException{ //throws的作用:声明可能引发的异常类
  30. if(age<=0||age>145){
  31. //throw的作用:抛出创建好的异常对象。
  32. throw new AgeException("年龄超过限制了"); //构建出一个异常对象, 如果满足条件了就构建异常对象。
  33. }
  34. this.age = age;
  35. }
  36. }