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?
- public static void main( String [] args ) {
- System.out.println( foo() );
- }
- public int foo() {
- try {
- throw new RuntimeException();
- } catch ( RuntimeException e ) {
- System.err.println( "Caught" );
- throw e;
- } finally {
- System.err.println( "Finally" );
- return 1;
- }
- }
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.