• java 自定义异常


    异常注意事项
    * a:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)
    * b:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
    * c:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
    * B:如何使用异常处理
    * 原则:如果该功能内部可以将问题处理,用try,如果处理不了,交由调用者处理,这是用throws
    * 区别:
    * 后续程序需要继续运行就try
    * 后续程序不需要继续运行就throws

    * 如果JDK没有提供对应的异常,需要自定义异常。

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

        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
       person p= new person();
       p.setAge(-17);
       System.out.println(p.getAge());
       
        }
    
    }
    class person {
        private String name;
        private int age;
        
        public person() {
            super();
            // TODO Auto-generated constructor stub
        }
        public person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) throws ageoutofboundexception {
            if(age>0 && age<=150){
                this.age=age;
            }else{
             throw new ageoutofboundexception("非法年龄");
        }
        
       }
    }

     

    class AgeOutOfBoundsException extends Exception {

    public AgeOutOfBoundsException() {
    super();

    }

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

    }

    }

     

  • 相关阅读:
    快速入门各种跨域
    常用知识点
    比较少用的格式
    git
    “没有用var声明的为全局变量”这种说法不准确
    类数组对象
    函数上下文的变量对象实例
    var a =10 与 a = 10的区别
    原型链与作用域链、执行上下文
    闭包的作用
  • 原文地址:https://www.cnblogs.com/yimian/p/6537906.html
Copyright © 2020-2023  润新知