Java_基础—自定义异常概述和基本使用

定义一个AgeOutOfBoundsException(年龄异常类),继承Exception, Alt + Shift + S → C 重写空参和有参的构造

package com.soar.exception;

public class Demo8_Exception {
    /*
     * * A:为什么需要自定义异常
        * 通过名字区分到底是什么异常,有针对的解决办法 
        * 举例:人的年龄
       * B:自定义异常概述
        * 继承自Exception
        * 继承自RuntimeException
       * C:案例演示
        * 自定义异常的基本使用

       自定义异常其实就是取决于它的名字
     */
    public static void main(String[] args) {
    }

}
class AgeOutOfBoundsException extends Exception{

    public AgeOutOfBoundsException() {
        super();    
    }

    public AgeOutOfBoundsException(String message) {
        super(message); 
    }

}

Person类的SetAge方法 抛出 异常

public void setAge(int age) throws AgeOutOfBoundsException {
        if(age > 0 && age <=150){
        this.age = age;
        }else{
            //Exception e = new AgeOutOfBoundsException("年龄非法");
            //throw e;
            throw new AgeOutOfBoundsException("年龄非法");  //等价于上面的写法
        }
    }

/*
   Exception in thread "main" com.soar.exception.AgeOutOfBoundsException: 年龄非法
    at com.soar.exception.Person.setAge(Demo6_Exception.java:61)
    at com.soar.exception.Demo6_Exception.main(Demo6_Exception.java:29)
*/
posted @ 2017-07-20 11:52  Soar_Sir  阅读(184)  评论(0编辑  收藏  举报