class LanPingException extends Exception
{
LanPingException(String message)
{
super(message); //重写父类的构造方法:Exception(String message)。
}
}
class MaoYanException extends Exception
{
MaoYanException(String message)
{
super(message); //重写父类的构造方法:Exception(String message)。
}
}
class NoPlanException extends Exception
{
NoPlanException(String msg)
{
super(msg); //重写父类的构造方法:Exception(String msg)。
}
}
//电脑类的描述
class Computer
{
private int state=3; //电脑状态:1,表正常,2,表蓝屏,3,冒烟
public void run()throws LanPingException,MaoYanException //这里必须声明异常
{
//对state进行判断后,就抛出相应的异常处理。
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 computer;
Teacher(String name) //对老师进行初始化。
{
this.name=name;
computer=new Computer();
}
public void prelect()throws NoPlanException
{
try
{
computer.run(); //运行时,状态可能异常
}
catch (LanPingException e) //捕获蓝屏
{
computer.restart();
}
catch (MaoYanException e) //捕获冒烟
{
test();
throw new NoPlanException("课时无法继续"+e.msg);
}
System.out.println("讲课");
}
public void test()
{
System.out.println("同学们练习");
}
}
class test
{
public static void main(String[] args)
{
Teacher t =new Teacher("毕老师");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString()); //
System.out.println("换老师 ,或者放假。");
}
}
}
|
|