I was curious about whether the finally block or the exception block would execute first (I always assumed the exception block executed first), so I tried the following code:
class Finally
{
publicstaticvoid main(java.lang.String[] args)
{
try
{
System.out.println( "Throwing exception" );
String sPointer = null;
int i = sPointer.length();
System.out.println( "Should never get here." );
}
catch( NullPointerException e )
{
System.err.println( "And very last of all: " + e );
}
finally
{
System.out.println( "Finally comes before exception block." );
}
System.out.println( "This gets executed before the catch! Why is that?" );
}
}
I discovered that the finally block is executed before the catch. But I was really surprised to see the code after the try\catch\finally executed before the catch block.