Java如何使用finally块来捕捉异常?

在Java编程中,如何使用finally块来捕捉异常?

此示例显示如何使用finally块来通过使用e.getMessage()捕获运行时异常(Illegalargumentexception)。

package com.yiibai;

public class UseOfFinally { public static void main(String[] argv) { new UseOfFinally().doTheWork(); } public void doTheWork() { Object o = null; for (int i = 0; i < 5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println("Error: (" + e.getMessage() + ")."); return; } finally { System.err.println("All done"); if (o == null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) throw new IllegalArgumentException("Don't like type " + type); return new Object(); } } 
Java

上述代码示例将产生以下结果 -

All done
Error: (Don't like type 1).
All done
java.lang.Object@2a139a55
Shell

示例-2

以下是java中使用finally块捕捉异常的另一个示例:

package com.yiibai;

public class UseOfFinally2 { public static void main(String[] args) { try { int data = 25 / 5; System.out.println(data); } catch (NullPointerException e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } 
Java

上述代码示例将产生以下结果 -

5
finally block is always executed
rest of the code...

转载于:https://www.cnblogs.com/borter/p/9613525.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值