Java异常抛出及try,catch应用实例

时间:2021-08-14 02:59:51
 class lanpingException extends Exception
{
lanpingException(String msg)
{
super(msg);
}
} class maoyanException extends Exception
{
maoyanException(String msg)
{
super(msg);
}
} class Computer
{
private int state=2;
public void run()throws lanpingException,maoyanException
{
if(state==1)
{
throw new lanpingException("lanping!!!");
}
if(state==2)
{
throw new maoyanException("maoyan!!!");
}
System.out.println("run bat");
}
public void reset()
{
state=0;
System.out.println("computer reset!");
}
} class Teacher
{
private String name;
private Computer comp;
Teacher(String name)
{
this.name=name;
comp=new Computer();
}
public void prelect()throws maoyanException
{
try
{
comp.run();
System.out.println(name+" speak");
}
catch(lanpingException e)
{
System.out.println(e.toString());
comp.reset();
prelect();
}
catch(maoyanException e)
{
System.out.println(e.toString());
test();
throw e;
}
}
public void test()
{
System.out.println("test yourself!");
}
} class Kandra
{
public static void main(String[] args)
{
Teacher pp=new Teacher("cao");
try
{
pp.prelect(); }
catch(maoyanException e)
{
System.out.println("......");
}
}
}