您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java 实例 - Finally的用法

2026/1/11 19:28:47发布27次查看
java 中的 finally 关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行 。
以下实例演示了如何使用 finally 通过 e.getmessage() 来捕获异常(非法参数异常):
/* author by w3cschool.cc 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 实例 - finally的用法的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product