异常经典例子

要求:

老师用电脑上课。
 开始思考上课中出现的问题。
 比如问题是
 电脑蓝屏。
 电脑冒烟。
 要对问题进行描述,封装成对象。
 可是当冒烟发生后,出现讲课进度无法继续。
 出现了讲师的问题:课时计划无法完成。

//蓝屏异常
class BlueException extends Exception
{
	BlueException(String msg)
	{
		super(msg);
	}
}

// 冒烟异常
class SmokeException extends Exception
{
	SmokeException(String msg)
	{
		super(msg);
	}
}

// 无法按时完成课程计划异常
class NoPlanException extends Exception
{
	NoPlanException(String msg)
	{
		super(msg);
	}

	public String toString()
	{
		return "课时异常,请校长定夺!!!";
	}

	public String getMessage()
	{
		return "课时异常,请校长定夺!!!";
	}
}

class Compu
{
	private int flag = 3;

	public void reset()
	{
		flag = 1;
		System.out.println("电脑重启。。。");
	}

	public void run() throws SmokeException, BlueException
	{
		if (flag == 2)
		{
			throw new SmokeException("冒烟了,损坏了");
		}
		if (flag == 3)
		{
			throw new BlueException("蓝屏了,需要重启。。。");
		}
		System.out.println("电脑运行了,耶!!!");
	}
}

class Teachers
{
	private String name;
	private Compu com;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	Teachers(String name)
	{
		this.name = name;
		com = new Compu();
	}

	public void teache() throws NoPlanException
	{
		try
		{
			com.run();
		} catch (BlueException e)
		{
			com.reset();
			System.out.println("电脑正常运行,上课");
		} catch (SmokeException e)
		{
			testtest();
			throw new NoPlanException(this.getName() + "电脑崩溃,课时无法正常完成");
		}
	}

	public void testtest()
	{
		System.out.println("练习");
	}

}

public class ExceptionLizi
{

	public static void main(String[] args)
	{
		// FLY 自动生成的方法存根
		Teachers tc = new Teachers("张老师");
		try
		{
			tc.teache();
		} catch (NoPlanException e)
		{
			System.out.println(e.toString());
			// e.printStackTrace();
			System.out.println("换老师或者放假");
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值