// 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;
}
}
}
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. |
|