自定义异常

/*
自定义异常:
  1)定义一个类继承Exception
  2)在自定义异常类虫提供两个构造方法。
  3)在需要的位置通过throw抛出异常对象。
  4)throw所在的方法通过throws声明该异常
  5)调用方法时,需要对受检异常预处理
*/

package day_18;
public class ageOverFlowException extends Exception { // 1)定义一个类继承Exception // 2)在自定义类中提供两种构造方法(1.无参构造方法 2.带字符串构造方法) public ageOverFlowException() { } public ageOverFlowException(String message) { super(message); } } package day_18; public class Person { private String name; private int age; private String sex; public Person() { } public Person(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) throws ageOverFlowException { // 4)throw所在的方法通过throws声明该异常对象 if(age>=0 && age<=120){ this.age = age; } else{ //年龄不合法,抛出一个异常 // 3)在需要的位置通过throw抛出异常对象 throw new ageOverFlowException("年龄越界"); } } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } } package day_18; public class Tset_Exception2 { public static void main(String[] args) { Person person=new Person(); person.setName("张三"); try { // 5)对受检异常进行预处理,捕获异常 person.setAge(2000); } catch (ageOverFlowException e) { e.printStackTrace(); } person.setSex("男"); System.out.println(person); } }

  

posted @ 2019-08-02 13:17  石乐智先生  阅读(194)  评论(0编辑  收藏  举报