java学习11天-自定义异常&异常转换(实例应用)

来源:互联网 发布:软件规格型号怎么写 编辑:程序博客网 时间:2024/04/28 08:47

想要很好的运用异常光靠系统自带的异常体系是不够的,这时候我们就需要自定义异常,自定义异常是一定要继承异常体系的(Exception编译异常runtimeException运行时异常),只有这样才能被throw和throws关键字操作。一起来看案例里吧。

java学习11天-自定义异常&异常转换(实例应用)

源代码如下,需要的收藏吧:

//异常转换实际应用

class NoPlanException extends Exception

{

NoPlanException(String msg)

{

super(msg);

}

}

class LanPingException extends Exception

{

LanPingException(String msg)

{

super(msg);

}

}

class MaoYanException extends Exception

{

MaoYanException(String msg)

{

super(msg);

}

}

class Computer

{

private int state=2;//电脑运行状态标识:0:正常 1:蓝屏 2:冒烟

public void run()throws LanPingException,MaoYanException

{

if (state==1)

{

throw new LanPingException("蓝屏啦。。");

}

if (state==2)

{

throw new MaoYanException("冒烟啦。。");

}

System.out.println("电脑运行中。。");

}

public void reset()

{

state=0;

System.out.println("电脑重启了");

}

}

class Teacher

{

private String name;

private Computer comp;

Teacher(String name)

{

this.name=name;

comp=new Computer();

}

public void prelect()throws NoPlanException

{

try

{

comp.run();

}

catch (LanPingException e)

{

System.out.println(e.toString());

comp.reset();

prelect();

}

catch (MaoYanException e)

{

System.out.println(e.toString());

test();

throw new NoPlanException(name+":没法儿工作了");

}

}

public void test()

{

System.out.println("做练习吧!");

}

public String getName()

{

return name;

}

}

public class Exceptiontest

{

public static void main(String[] args)

{

Teacher t=new Teacher("滑稽老师");

try

{

t.prelect();

System.out.println(t.getName()+"正在讲课中。。");

}

catch (NoPlanException e)

{

System.out.println(e.toString());

System.out.println("换人吧。");

}

}

}

运行结果(运行状态依次为:0、1、2):

java学习11天-自定义异常&异常转换(实例应用)

喜欢我的记得订阅哦,持续更新ing。。。

欢迎一起讨论java知识。

0 0
原创粉丝点击