class LanPingException extends Exception
{
LanPingException(String message)
{
super(message);
}
}
class MaoYanException extends Exception
{
MaoYanException(String message)
{
super(message);
}
}
class NoPlanException extends Exception
{
NoPlanException(String msg)
{
super(msg);
}
}
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()
{
state = 1;
System.out.println("电脑重启");
}
}
class Teacher
{
private String name;
private Computer cmpt;
Teacher(String name)
{
this.name = name;
cmpt = new Computer();
}
public void prelect()throws NoPlanException
{
try
{
cmpt.run();
}
catch (LanPingException e)
{
cmpt.reset();
}
catch (MaoYanException e)
{
test();
throw new NoPlanException("课时无法继续"+e.getMessage());
}
System.out.println("讲课");
}
public void test()
{
System.out.println("练习");
}
}
class ExceptionTest
{
public static void main(String[] args)
{
Teacher t = new Teacher("毕老师");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString());
System.out.println("换老师或者放假");
}
}
}
心得分享: 这个程序描述现实问题:老师带电脑讲课,电脑会出现蓝屏,冒烟问题,蓝屏问题老师自己解决就可以再次上课,如果出现电脑冒烟,老师就不能继续上课,冒烟这个问题老师解决不了,所以给老板另一项方式说,课程无法继续,老板只能通过放假或者换老师来解决问题。
上面程序涉及四个对象,1,电脑对象。2,毕老师,3,异常对象,4,老板对象。上面最最重要的是 异常转换,让其他调用者容易理解的方式去处理异常。
|
|