eyt*
August 8, 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.


Posted 9 years, 6 months ago on August 8, 2012
The trackback url for this post is https://www.eyt.ca/blog/bblog/trackback.php/142/

Comments have now been turned off for this post. If you want to share something, please e-mail me.

Navigation

Recent Posts

eyt*