Java基础复习---异常练习(一):实现老师用电脑上课

package exceptiontest;
/**
 * 代码描述:
 * 实现老师用电脑上课
 * 
 * 上课时可能出现的问题:
 * 1.电脑冒烟
 * 2.蓝屏
 * 
 * 要对问题进行描述,封装成对象
 * 
 * 可是当冒烟发送时,导致讲课无法继续
 * 这时就出现了,讲师的问题,课时计划无法完成
 * @author Administrator
 *2016年11月1日 09:46:25
 */

public class ExceptionTest {
	public static void main(String[]  agrs)  {
		Teacher t = new Teacher("dby");
		try {
			t.prelect();
		} catch (NoPlanException e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString());
			System.out.println("换老师");
			System.out.println("放假");
			e.printStackTrace();
		}
		
	}
}
<pre name="code" class="java">package exceptiontest;

public class LanPingException extends Exception {

	LanPingException(String message){
		super(message);
	}
}


 
 
<pre name="code" class="java">package exceptiontest;

public class MaoYanException extends Exception {

	public MaoYanException(String message) {
		// TODO Auto-generated constructor stub
		super(message);
	}
	
}


 
 
<pre name="code" class="java">package exceptiontest;

public class NoPlanException extends Exception {
	NoPlanException(String message){
		super(message);
	}
}


 
 
</pre><pre name="code" class="java"><pre name="code" class="java">package exceptiontest;
/**
 * 一台电脑有三个状态
 * 运行()声明电脑可能发生的异常,LanPingException,MaoYanException
 * 1 正常运行
 * 2 电脑蓝屏 此时,抛出该异常LanPingException
 * 3 电脑冒烟 此时,抛出该异常MaoYanException
 * 
 * 内部
 * 如果要抛出异常,此时前提必须是是函数对该异常有声明
 * 如果要处理异常,则在try-catch中完成
 * @author Administrator
 *
 */
public class Computer {
	private int state = 3;
	public void run() throws LanPingException, MaoYanException {
		if(state == 2)
			throw new LanPingException("蓝屏了");
		if(state == 3)
			throw new MaoYanException("冒烟了");
		
		System.out.println("电脑运行");
	}
	
	public void reset(){
		System.out.println("电脑重启");
		
	}
	
}


 
 

package exceptiontest;
/**
 * 某教师需要使用电脑
 * 初始化,教师姓名,并为其分配电脑
 * 
 * 教师上课
 * 调用运行电脑()
 * 因为此时运行电脑()可能出现异常,所以需要进行异常处理
 * 处理 LanPingException e     重启电脑cup.reset();
 * 处理 MaoYanException e  先让学生做练习,紧接着教师的教学计划受影响
 * 		抛出 教学计划受影响这一异常  在老师上课()中进行异常NoPlanException的处理
 * 												由于MaoYanException.message
 * 												换老师或者放假
 * @author Administrator
 *
 */

public class Teacher {
	private String name;
	private Computer cup;
	
	Teacher(String name){
		this.name = name;
		cup = new Computer();
	}
	
	public void prelect() throws NoPlanException{
		
		try{
			cup.run();
			}
		catch(LanPingException e){
			cup.reset();
		}
		catch(MaoYanException e){
			test();
			throw new NoPlanException("课时无法继续,因为电脑"+ e.getMessage());
			//test();//Unreachable code  throw  不执行
		}
		System.out.println("老师讲课");
	}
	
	public void test(){
		System.out.println("练习");
	}
}


参考文献:传智播客毕向东Java基础视频教程-day09-12-面向对象(异常练习)

猜你喜欢

转载自blog.csdn.net/u011296723/article/details/52993104
今日推荐