java异常例子_Java异常的例子

对于检查型异常,Java强迫程序必须进行处理,处理的方式有以下两种:

1.声明抛出异常:不在当前方法内处理异常,而是把异常抛出到调用方法中;

2.捕获异常:使用try、catch和finally构成的语句块,捕获所发生的异常,进行相应的处理。

3.除了使用系统预定义的异常类外,用户还可以声明自己的异常类。

下面代码的输出是:

before call f2()

before call f3()

before call f4()

before call f5()

before

cn.edu.uibe.oop3.MyException: chu cuo la

at cn.edu.uibe.oop3.ExpDemo2.f5(ExpDemo2.java:36)

at cn.edu.uibe.oop3.ExpDemo2.f4(ExpDemo2.java:30)

at cn.edu.uibe.oop3.ExpDemo2.f3(ExpDemo2.java:25)

at cn.edu.uibe.oop3.ExpDemo2.f2(ExpDemo2.java:14)

at cn.edu.uibe.oop3.ExpDemo2.f1(ExpDemo2.java:8)

at cn.edu.uibe.oop3.ExpDemo2.main(ExpDemo2.java:46)

chu cuo la

Any Time

after call f3()

after call f2()

packagecn.edu.uibe.oop3;

classMyExceptionextendsException{

MyException(){

super("myexception");

}

MyException(String msg){

super(msg);

}

}

publicclassExpDemo2 {

publicvoidf1(intn){

System.out.println("before call f2()");

f2(n);

System.out.println("after call f2()");

}

publicvoidf2(intn){

System.out.println("before call f3()");

try{

f3(n);

}catch(MyException e){

e.printStackTrace();

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

}finally{

System.out.println("Any Time");

}

System.out.println("after call f3()");

}

publicvoidf3(intn)throwsMyException{

System.out.println("before call f4()");

f4(n);

System.out.println("after call f4()");

}

publicvoidf4(intn)throwsMyException{

System.out.println("before call f5()");

f5(n);

System.out.println("after call f5()");

}

publicvoidf5(intn)throwsMyException{

System.out.println("before");

if(n<0){

thrownewMyException("chu cuo la");

}else{

System.out.println("success!");

}

System.out.println("after");

}

publicstaticvoidmain(String[] args) {

ExpDemo2 ed =newExpDemo2();

ed.f1(-100);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值