/*需求:对老师用电脑上课可能出现的异常进行处理.
开始思考上课中出现的问题
电脑蓝屏 电脑冒烟
要对问题进行描述,封装成对象;
可是冒烟发生后,出现讲课无法继续;
出现了讲师的问题,课时计划无法完成.
*/
- class LanPingException extends Exception//蓝屏异常
- {
- LanPingException(String message)
- {
- super(message);
- }
- }
- class MaoYanException extends Exception//冒烟一异常
- {
- MaoYanException(String message)
- {
- super(message);
- }
- }
- class NoPlanException extends Exception//课时计划异常
- {
- NoPlanException(String message)
- {
- super(message);
- }
- }
- class Computer //创建一个类包括电脑的功能
- {
- private int state = 3;//键入不同的值可能导致电脑出现异常
- public void run() throws LanPingException,MaoYanException
- {
- if (state == 2)
- throw new LanPingException("蓝屏了");
- if (state == 3)
- throw new MaoYanException("冒烟了");
- System.out.println("电脑运行");
- }
- public void reset()//重启功能
- {
- state = 1;
- System.out.println("电脑重启");
- }
- }
- class Teacher//创建一个类包括:老师用电脑讲课及安排小练习
- {
- private String name;//定义老师名字
- private Computer cmpt;//定义所使用电脑
- Teacher(String name)//自定义一个构造方法
- {
- this.name = name;
- cmpt = new Computer();
- }
- public void prelect() throws NoPlanException//声明课时计划异常
- {
- try//处理异常
- {
- cmpt.run();
- }
- catch (LanPingException e)//蓝屏异常处理
- {
- cmpt.reset();//电脑蓝屏重启
- }
- catch (MaoYanException e)//电脑冒烟异常处理
- {
- test();
- throw new NoPlanException("课时无法继续"+e.getMessage());//电脑冒烟异常抛出
- }
- System.out.println("讲课");
- }
- public void test()
- {
- System.out.println("做练习");
- }
- }
- class ExceptionTest
- {
- public static void main(String[] agrs)
- {
- Teacher t = new Teacher("老师");
- try
- {
- t.prelect();
- }
- catch (NoPlanException e)//课时计划异常处理
- {
- System.out.println(e.toString());
- System.out.println("换老师或者放假");
- }
-
- }
- }
复制代码
|
|