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);
}
}
}
异常处理小练习,异常转换
最新推荐文章于 2021-02-12 15:36:06 发布