When the exception is thrown, the execution of the usual method will make a steep nonlinear turn. Depend on how the method is encoded, exceptions can even cause the method to return prematurely. This is a problem in some methods. For example, if a method opens a file item and closes it and then exits, you do not want the code that closes the file to be bypassed by the exception handling mechanism. Finally keywords are designed to handle such accidents.
Finally create a code block. This code block is executed before another try/catch appears after one try/catch block is completed. Finally block will be executed regardless of whether there is an exception thrown or not. If the exception is thrown, finally will be executed even without a catch clause that matches the exception. A method will be returned from a try/catch block to the calling program any time it is called, after an uncaught exception or an explicit return statement, the finally clause will still be executed before the method returns. This is useful when closing the file handle and freeing any other resources that are allocated at the beginning of the method. The finally clause is optional, either with or without. However, each try statement requires at least one catch or finally clause.
The following example shows 3 different exit methods. Each executes the finally clause:
// Demonstrate finally.class FinallyDemo { // Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } // Return from within a try block. static void procB() { try { System.out.println("inside procB"); re turn; } finally { System. out.println("procB's finally"); } } // Execute a try block normally.static void procC() { try { System.out.println("inside procC"); } finally { System.out.println(" procC's finally"); } } public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception catch"); } procB(); procC( ); }}
In this example, procA( ) interrupts the try prematurely by throwing an exception. The final clause is executed on exit. The procB( ) try statement exits through a return statement. The finally clause is executed before procB( ) returns. In procC(), the try statement is executed normally without errors. However, finally block will still be executed.
Note: If the finally block is used in conjunction with a try, the finally block will be executed before the end of the try.
The following is the output generated by the above program:
inside procAprocA's finallyException caughtinside procBprocB's finallyinside procCprocC's finally