Previous | Home | Next |
The finally block always executes when the try block exits. Finally block ensure that necessary portion of code must execute even if anything unexpected occur then . Except exception handling finally useful for writing cleanup code even accidentally bypassed by a return, continue, or break. Following Example demonstrate it.
/* * This file has been saved as ShowFinaly.java * This File Shows implementation of Finally */ package UsingFinally; class impFinally { public void FinallySemo() { int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0]=6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } public class ShowFinally { public static void main(String[] str) { impFinally obj=new impFinally(); obj.FinallySemo(); } }
Output:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
Previous | Home | Next |