zoukankan      html  css  js  c++  java
  • 异常的真实应用

    /**
     * 要求:老师用电脑讲课发生蓝屏异常和死机异常机器处理
     * 
     * @author Administrator
     *
     */
    
    class Teacher
    {
    	private String name;
    	private Computer com;
    	public Teacher(String name){
    		this.name=name;
    		com=new Computer();
    	}
    	
    	public void teach() throws NoPlanException{
    		try{
    			com.run();
    		System.out.println(name+"开始上课");
    	   
    		}catch(LanPingException e){
    			System.out.println(e.toString());
    			com.reset();//调用重启方法
    			teach();
    		}
    		catch(SiJiException e){
    			System.out.println(e.toString());
    			test();//调用休息方法
    			throw new NoPlanException("任务完不成");//抛出不能完成任务的方法给调用者
    		}
    	 }	
    	public void test(){//休息方法
    		System.out.println("大家休息");
    	}
    }
    class Computer{
    	int status=(int)(Math.random()*3);//定义状态变量获取随机数,0表示正常,1表示蓝屏异常,2,表示死机异常
    	public void run()throws LanPingException,SiJiException
    	{
    			if(status==1){//不同情况抛出不同异常
    				throw new LanPingException("你的电脑蓝屏了");
    			}
    			
    			if(status==2){
    				throw new SiJiException("你的电脑坏掉了!");
    			}
    			
    			System.out.println("电脑运行");
    		
    	}
    	public void reset(){
    		System.out.println("电脑重新启动!");
    		status=0;//重启后电脑正常
    	}
    }
    class LanPingException extends Exception{//蓝屏异常
    	LanPingException(String s){
    		super(s);
    	}
    }
    class SiJiException extends Exception{//电脑不会用异常
    	SiJiException(String s){
    		super(s);
    	}
    }
    class NoPlanException extends Exception{//任务完不成的异常
    	NoPlanException(String s){
    		super(s);
    	}
    }
    public class ExceptionApplication {
    	public static void main(String[] args) {
    		Teacher t=new Teacher("李老师");
         	try{//获取任务完不成的异常,然后处理
         		t.teach();
         	}catch(NoPlanException e){
         		System.out.println(e.toString());
         	    System.out.println("换一个老师");
         		
         	}
    	}
    }
    

    //若status为0,

    电脑运行
    李老师开始上课

    //若status为1

    LanPingException: 你的电脑蓝屏了
    电脑重新启动!
    电脑运行
    李老师开始上课

    //若status为2

    SiJiException: 你的电脑坏掉了!
    大家休息
    NoPlanException: 任务完不成
    换一个老师

  • 相关阅读:
    185. [USACO Oct08] 挖水井
    JavaEE Tutorials (9)
    vjudge A
    HDU 2089 不要62
    国庆 day 2 下午
    国庆 day 2 上午
    国庆 day 1 下午
    P2899 [USACO08JAN]手机网络Cell Phone Network
    洛谷 P1690 贪婪的Copy
    洛谷 P2209 [USACO13OPEN]燃油经济性Fuel Economy
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4492751.html
Copyright © 2011-2022 走看看