eyt*
Aug 08, 2012

Don’t return from within finally

Earlier today, I was debugging some seemed to be some pretty straight-forward code. The code effectively was the following function. What would you expect the output of this class to be?

  1. public static void main( String [] args ) {
  2.   System.out.println( foo() );
  3. }
  4. public int foo() {
  5.   try {
  6.     throw new RuntimeException();
  7.   } catch ( RuntimeException e ) {
  8.     System.err.println( "Caught" );
  9.     throw e;
  10.   } finally {
  11.     System.err.println( "Finally" );
  12.     return 1;
  13.   }
  14. }

If you expected an exception to be percolated out as I was, you are wrong. It actually turns out that the above returns 1 and ignores the exception that was just raised. Just something subtle to keep an eye out for.

Filed In

Navigation

eyt*