Java 实例 - Finally的用法

Java 教程 · 2019-02-11 09:59:39

Java 中的 Finally 关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行 。

以下实例演示了如何使用 finally 通过 e.getMessage() 来捕获异常(非法参数异常):

ExceptionDemo2.java 文件

public class ExceptionDemo2 { public static void main(String[] argv) { new ExceptionDemo2().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("都已执行完毕"); if (o==null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) throw new IllegalArgumentException ("不是指定的类型: " + type); return new Object(); } }

以上代码运行输出结果为:

都已执行完毕
java.lang.Object@7852e922
Error: (不是指定的类型:1).
都已执行完毕

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

Learning Web App Development

Learning Web App Development

Semmy Purewal / O'Reilly Media / 2014-3-3 / USD 29.99

Grasp the fundamentals of web application development by building a simple database-backed app from scratch, using HTML, JavaScript, and other open source tools. Through hands-on tutorials, this pract......一起来看看 《Learning Web App Development》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具