需求:毕老师用电脑上课
1.开始思考上课中出现的问题:1.电脑蓝屏2.电脑冒烟
2.要对问题进行描述,封装成对象。
可是当冒烟发生后,出现讲课进度无法继续
出现了讲师的问题,课程计划无法完成
//定义蓝屏异常,封装成对象
class LanPingException extends Exception
{
LanPingException(String message)
{
super(message);//父类Exception有getMessage方法,用super调用,无需重写
}
}
//定义冒烟异常,封装成对象,
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();
//创建 NoPlanException,函数上声明NoPlanException后,抛给主函数,主函数try catch
throw new NoPlanException("课时无法继续"+e.getMessage());
}
System.out.println("讲课");
}
public void test()
{
System.out.println("练习");
}
}
class ExceptionTest
{
public static void main(String[] args)
{
Teacher t = new Teacher("毕老师");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString());
System.out.println("换老师或者放假");
}
}
}
网友评论