/*
需求:老师调用电脑上课,电脑可能出现蓝屏或冒烟异常
当电脑蓝屏时,需重启电脑
当电脑冒烟时,需运用课时无法进行异常解决
*/
现在想要让电脑重启后,继续调用run() , 可是调用run()又需对异常进行抛出或声
这样问题就来了:
1、 如果蓝屏这个问题,需要在函数内部解决,不希望被抛出,代码应该怎么写?
2、如果蓝屏主个问题,可以抛出,由调用者解决,那应该怎么写?
==================程序代码=========================
class Teacher6
{
String name;
Computer6 cmpt;
Teacher6(String name)
{
this.name = name;
}
//讲课
public void prelect() throws NoPlanException,
{
try
{
cmpt = new Computer6();
cmpt.run();
}
catch (LanPingException6 e)
{
cmpt.reset();
cmpt.run();//异常需被抛出或声明
}
catch(MaoYanException6 e)
{
throw new NoPlanException("换电脑");
}
System.out.println("老师讲课");
}
}
class Computer6
{
private int status = 2;
//电脑运行
public void run() throws LanPingException6,MaoYanException6
{
if (status==2)
throw new LanPingException6("电脑蓝屏了!");
if(status==3)
throw new MaoYanException6("电脑冒烟了!");
System.out.println("电脑运行");
}
//电脑重启
public void reset()
{
System.out.println("电脑重启");
status = 1;
}
}
//蓝屏异常
class LanPingException6 extends Exception
{
LanPingException6(String msg)
{
super(msg);
}
}
//冒烟异常
class MaoYanException6 extends Exception
{
MaoYanException6(String msg)
{
super(msg);
}
}
//课时无法进行异常
class NoPlanException6 extends Exception
{
NoPlanException6(String msg)
{
super(msg);
}
}
class ExceptionDemo6
{
public static void main(String[] args)
{
Teacher6 t = new Teacher6("qu");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString());
}
System.out.println("Hello World!");
}
}
==========================运行截图=========================
|
组图打开中,请稍候......
|