Java Examples - Usage of finally

Java 实例Java Examples

In Java, the finally keyword is generally used together with try. After the program enters the try block, no matter whether the program terminates due to an exception or is terminated by returning in some other way, the content of the finally block will definitely be executed.

The following example demonstrates how to use finally to catch an exception (illegal argument exception) through e.getMessage():

ExceptionDemo2.java file

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("All have been executed"); if (o==null) System.exit(0); } System.out.println(o); } } public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) throw new IllegalArgumentException ("Not the specified type:" + type); return new Object(); } }

The output of the above code is:

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

Java 实例Java Examples

Other extensions