异常处理

来源:互联网 发布:淘宝平台技术费 编辑:程序博客网 时间:2024/06/06 16:46
package exceptionTest;/* * 比老师用电脑讲课 *  * 出现的问题: * 1,电脑蓝屏 * 2,电脑冒烟, * 3,当电脑冒烟后,讲课无法进行,需要采取下一步计划,放假或者换电脑? *  * 要对问题进行描述,封装成对象 *  *  */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);}public void test(){System.out.println("做练习");}}class Computer{private int state=1;  //1表示正常,2表示蓝屏,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   //此方法调用了computer.run,需要解决问题,且电脑冒烟毕老师解决不了,继续抛{try{cmpt.run();}catch(LanPingException e){System.out.println(e.getMessage());cmpt.reset();}catch(MaoYanException e){throw new NoPlanException("课时无法继续");//冒烟了,继续抛给下一个方法处理}System.out.println("毕老师讲课了");}}public class ExceptionTest2 {public static void main(String[] args){Teacher t= new Teacher("毕老师");try{t.prelect();}catch(NoPlanException e){System.out.println(e.getMessage());e.test();System.out.println("换电脑或者放假");}}}

0 0
原创粉丝点击