您好,欢迎访问一九零五行业门户网

Java 实例 - Finally的用法

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的用法的内容。
其它类似信息

推荐信息