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

毕老师在上机课中面对计算机可能遇到的蓝屏和冒烟异常,通过重启解决蓝屏问题,并将冒烟异常抛出,演示如何在教育场景下处理计算机故障。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

//电脑类,运行时可能出现故障——蓝屏,冒烟,
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("调课");
		}
			
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值