IT Certificaions

Google Cloud Platform

Friday, September 30, 2011

finally in Exception Handling in Java

finally block always executes after try block. So finally block will be executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break
You can put cleanup code in a finally block that is always a good practice, even when no exceptions are anticipated.



public void writeData() {
    PrintWriter out = null;

    try {
        System.out.println("Entering try statement");
        out = new PrintWriter(
                          new FileWriter("myFile.txt"));
            for (int i = 0; i < SIZE; i++)
                out.println("Value at: " + i + " = " 
                             + vector.elementAt(i));
                  
    } catch (ArrayIndexOutOfBoundsException e) {
         System.err.println("ArrayIndexOutOfBoundsException: " 
                     +   e.getMessage());
                                 
    } catch (IOException e) {
         System.err.println("IOException: " 
                             +  e.getMessage());
                                 
    } finally {
         if (out != null) {
             System.out.println("Closing PrintWriter");
             out.close();
                
         } 
         else {
             System.out.println("PrintWriter not open");
         }
     }
}


When finally may not execute
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. For example if a live thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues because there may be other threads doing some other works..