The Finally key in Java is generally used together with try. After the program enters the try block, whether the program is terminated due to an exception or otherwise, the contents of the finally block will definitely be executed.
The following example demonstrates how to use finally to catch exceptions (illegal parameter exceptions) through 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(); } }
The output result of running the above code is:
都已执行完毕 java.lang.Object@7852e922 Error: (不是指定的类型:1). 都已执行完毕
Above It is the content of Java Example-Finally usage. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!