A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 周发建 中级黑马   /  2016-3-22 09:40  /  409 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一、异常(一)异常
程序在运行是发生的不正常情况
异常体系:异常有很多,将异常封装成对象,形成了异常体系
Throwable        可抛性 throw throws
|--Error        错误,一般不针对处理,直接修改程序
|--Exception 异常 try..catch..finally        throw throws
|--RuntimeException        运行是异常:编译是不检测异常
注意:子类在覆盖父类方法时,只能抛出父类异常的子类或子集。
异常就是运行是遇到的问题,java中都对异常进行了描述,如果java中没有描述的异常,就自定义描述。
[size=16.0000pt](二)定义异常
NoPlanException        课程进度无法完成
LanPingException        蓝屏
MaoYanException        冒烟
//电脑
class Computer{
        int status = 0;
        //运行
        public void run() throws LanpingException, MaoYanException{
                if(status ==1){
                        throw new LanpingException("电脑蓝屏了");
                }else if(status == 2){
                        throw new MaoYanException("电脑冒烟了");
                }else{
                        System.out.println("电脑成功运行");
                }
        }
        //重启
        public void restart() throws LanpingException, MaoYanException{
                System.out.println("电脑重启");
                status = 0;
                run();
        }
}
//老师
class Teacher{
        private String name;
        private Computer com;
        public Teacher(String name) {
                this.name = name;
                this.com = new Computer();
        }
        //讲课
        public void prelect() throws LanpingException, MaoYanException, NoPanException{
                try{
                        com.run();
                        System.out.println(name+"讲课");
                }catch(LanpingException e){
                        System.out.println(e.toString());
                        com.restart();
                        prelect();
                }catch(MaoYanException e){
                        System.out.println(e.toString());
                        test();
                        throw new NoPanException("课程无法继续,原因:电脑冒烟了");
                }
        }
        //练习
        public void test(){
                System.out.println("大家做练习");
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马