以下实例演示了如何使用 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的用法的内容。
