您的位置:首页 > 编程语言 > Java开发

Java day08 异常实例 上课时电脑出问题

2016-03-22 22:36 513 查看
//一般情况下,谁调用可能出现错误的方法,就把异常抛给谁
//异常说起来是参数对执行者造成问题,而不是执行者本身有问题,只能说执行者不完善

//场景描述:毕老师有一节上机课,机器可能出现故障

//电脑类,运行时可能出现故障——蓝屏,冒烟,
class Computer
{
private int status=2;
public void run()throws BlueScreenException,SmokingException
{
if(status==1)
throw new BlueScreenException("电脑蓝屏了");
else if(status==2)
throw new SmokingException("电脑冒烟了");
else
System.out.println("电脑正常启动");
}
public void reboot()
{
status=0;
System.out.println("电脑重启");
}
}
//老师类,上课时使用计算机可能出现异常,蓝屏异常可重启(计算机),冒烟异常抛出
class Teacher
{
private String name;
private Computer c;//电脑对象作为老师类的一个成员
Teacher(String name)
{
this.name=name;
c=new Computer();//初始化电脑对象
}
public void attend()throws NoPlan
{
try{
c.run();//?
}
catch(BlueScreenException e)
{
c.reboot();
}
catch(SmokingException e)
{
throw new NoPlan("课程计划无法继续"+e.getMessage());//当自己处理不了时,再次往外抛出——当执行到此句时,程序终止
//这个e是Smoking的e,它的字符串作为NoPlan构造函数的参数传给NoPlan
//test();
}
System.out.println("开始上课");
}
public void test()
{
System.out.println("做练习");
}
}
//蓝屏异常
class BlueScreenException extends Exception
{
//String msg;
BlueScreenException(String msg)
{
super(msg);
}
}
//冒烟异常
class SmokingException extends Exception
{
SmokingException(String msg)
{
super(msg);
}
}
//课程计划异常
class NoPlan extends Exception
{
NoPlan(String msg)
{
super(msg);
}
}
//教务处,也处理不了冒烟的电脑,只能通过间接方式调课
class ExceptionTest
{
public static void main(String[] args)
{
Teacher t=new Teacher("毕老师");
try
{
t.attend();
}
catch (NoPlan e)
{
System.out.println(e.toString());
System.out.println("调课");
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: