Exceptions (Cont.)


The finally Keyword
The finally statement lets you execute code, after try...catch, regardless of the result. A finally block typically contains cleanup code that recovers from partial execution of a try block. It is always a good practice to use finally clause after the try and catch block to handle an unexpected exception occurred in the try block. The finally block always executes when the try block exits and it is also useful to write the cleanup code within the finally block.

FinallyDemo.java (with a finally keyword)
public class FinallyDemo {
  public static void main( String[ ] args ) {
    try {
      int[ ] myNumbers = { 1, 2, 3 };
      System.out.println( myNumbers[10] );
    }
    catch ( Exception e ) {
      System.out.println( "Something went wrong." );
      e.printStackTrace( );      
    }
    finally {
      System.out.println( "The 'try catch' is finished." );
    }
  }
}
shell> java FinallyDemo          




      I feel bad for the homeless guy,    
      but I feel really bad for the homeless guy’s dog,    
      because he must be thinking    
      “Man, this is the longest walk ever.”