异常处理小练习,异常转换

package strange;

class Computer{//可能出现的情况判定也一起封在对象中
	private int state;
	public void setState(int state){
		this.state=state;
	}
	public void show()throws BRException
	{
		if(state==1)
			throw new BRException("someone is breaking the law");
		if(state==2)
			throw new TeException("explosion");
		System.out.println("showing pictures");
	}
	public void record(String a)throws BRException{//处理方式,处理后Exception类恢复正常;
		
		System.out.println(a+" is breaking the rules, making recordings");
		System.out.println("handle");
		state=0;
		show();
		
	}
}

class BRException extends Exception{
	BRException(String msg){
		super(msg);
	}
}

class TeException extends RuntimeException{
	TeException(String msg){
		super(msg);
	}
}

class ClassNoException extends Exception{
	ClassNoException(String msg){
		super(msg);
	}
}
class Supervisor{
	private String name;
	Computer cc;
	Supervisor(String name){
		this.name=name;	
		cc=new Computer();
	}
	public void monitor(int a,String b)throws BRException,ClassNoException
	{
		cc.setState(a);
		try
		{	
			cc.show();
		}
		catch(BRException e){
			cc.record(b);
		}
		catch(TeException e){
			throw new ClassNoException("电脑已坏, 故障现象"+e.getMessage());
			//处理不了的转换为其他可以处理的异常;
			/*一旦throw,程序就结束了,接下来不要再加其他语句,
			 * 一定要在catch种加东西,必须在throw之前类似的还有return;
			 */
		}
	}	
}



//----------------------------------------------------------------------------


public class Practise {

	public static void main(String[] args)throws BRException,ClassNoException {
		Supervisor ss=new Supervisor("LBR");
		int aa=2;
		String bb="xx";
		try{
			ss.monitor(aa,bb);
		}
		catch(ClassNoException e){
			System.out.println(e.getMessage()+","+"replace with a new one");
			aa=0;
			ss.monitor(aa,bb);
		}
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值