try-catch-finally (Visual J#) 

Visual Studio 2005

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.

try try-block catch catch-block(s) finally finally-block



Contains the code segment expected to raise the exception.


Contains the exception handler.


Contains the exception handler and the cleanup code.

The finally keyword is used to define a block of code following a try-catch exception block. The finally block is optional, and appears after the try block and after any catch blocks. The code in a finally block is guaranteed to be executed once, regardless of how the code in a try block executes. In normal execution, control reaches the end of the try block and then proceeds to the finally block, which typically performs any necessary cleanup.

If control leaves the try block because of a return, continue, or break statement, the contents of the finally block are still executed before control transfers out of the try block.

If an exception occurs in the try block, and there is an associated catch block to handle the exception within the method, control is transferred first to the catch block, and then to the finally block. If there is no local catch block to handle the exception, control is transferred first to the finally block, and then moves up the series of prior method calls until the exception can be handled.

// try-catch-finally
public class EHClass 
   public static void main(String [] args) 
         System.out.println("Executing the try statement.");
         throw new NullPointerException();
      catch(NullPointerException e) 
         System.out.println("Caught exception #1:" + e); 
         System.out.println("Executing finally block.");

Executing the try statement.
Caught exception #1:java.lang.NullPointerException
Executing finally block.

Community Additions