TryTest.java

Download this source file

// This class demonstrates how try blocks with finally clauses work.
// Can you predict the output of the program below?
// 
// Written 2001 by Wayne Pollock, Tampa Florida USA

class TryTest
{
   public static void main ( String [] args )
   {
      int i = bar();
      System.out.println( i );
   }

   static int bar ()
   {
      int i = 2;
      try
      {
        return ++i;
      }
      finally
      {  return i + i;
      }
   }
}

See the Answer






























Answer

The try block executes the return statement, which starts by adding one to i.  But before actually returning, the code in the finally clause is run.  In this case, that code executes a return, so the original return statement in the try block never finishes.

The final result is that 6 is returned and printed.


Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA