异常的练习:
老师用电脑上课。
开始思考上课中出现的问题。
比如问题是
电脑蓝屏。
电脑冒烟。
要对问题进行描述,封装成对象。
可是当冒烟发生后,出现讲课进度无法继续。
出现了讲师的问题:课时计划无法完成。
class Teacher
{
private Computer cmp;
public void shangKe()throws NoPlanException
{
cmp=new Computer();
try
{
cmp.run();
}
catch(LanPingException e)
{
cmp.recst();
}
catch(MaoYanException e)
{
throw new NoPlanException("上课无法继续,因为"+e.getMessage());
}
System.out.println("老师上课");
}
}
class LanPingException extends Exception
{
LanPingException(String m)
{
super(m);
}
}
class MaoYanException extends Exception
{
MaoYanException(String m)
{
super(m);
}
}
class NoPlanException extends Exception
{
NoPlanException(String m)
{
super(m);
}
}
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 recst()
{
System.out.println("电脑重启");
}
}
class ExceptionText
{
public static void main(String args[])
{
Teacher t=new Teacher();
try
{
t.shangKe();
}
catch(NoPlanException e)
{
System.out.println(e.toString());
}
}
}
运行结果:
NoPlanException: 上课无法继续,因为电脑冒烟了
以上这篇java异常处理的简单练习就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



