Easy Tutorial
❮ Thread Alive Java Object Clone ❯

Java Example - Usage of Finally

Java Examples

In Java, the finally keyword is generally used with try. After the program enters the try block, regardless of whether the program terminates due to an exception or other means, the code inside the finally block is guaranteed to execute.

The following example demonstrates how to use finally to catch exceptions (illegal argument exceptions) using 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 done");
            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:

All done
java.lang.Object@7852e922
Error: (Not the specified type: 1).
All done

Java Examples

❮ Thread Alive Java Object Clone ❯