/*
需求:毕老师用电脑上课
开始思考上课中出现的问题: 电脑蓝屏 ,电脑冒烟
要对问题进行描述,封装对象
可是当冒烟发生或,出现讲课进度无法继续。
出现了讲师的问题,课时计划无法完成。
*/
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; //定义一个状态值来表示是否出异常,1代表正常
public void run( ) throws LanpingException,MaoyanException
{
if(state==2)
throw new LanpingException( "蓝屏了");
if(state==3)
throw new MaoyanException("冒烟了");
System.out.println("电脑运行");
}
public void restart( )
{
state=1;
System.out.println("电脑重启");
}
}
class Teacher
{
private String name;
private Computer cmpt;
Teacher(String name)
{
this.name=name;
cmpt=new Computer( ); //如果这里换成 Computer cmpt=new Computer( );会出现空指针异常
}
public void prelect( )throws NoplanException //讲课
{
try
{
cmpt.run( );
}
catch (LanpingException e)
{
cmpt.restart( );
}
catch( MaoyanException e)
{
test( );//如果test放在throw 下面语句执行不到,编译会不通过
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.print("换老师,或者.....");
}
}
}
【java】毕向东异常练习
最新推荐文章于 2021-04-12 19:22:30 发布