finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code always executes whether or not exception has occurred. Using a finally block, lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest { public static void main(String[] args) { int a[]= new int[2]; System.out.println("out of try"); try { System.out.println("Access invalid element"+ a[3]); /* the above statement will throw ArrayIndexOutOfBoundException */ } finally { System.out.println("finally is always executed."); } } }
Output :
Out of try finally is always executed. Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.
No comments:
Post a Comment