Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Java's Try-Catch-Finally Edge Case Handling

View an in-depth explanation here - Compiling for the JVM - GuideWire Development

Take a look at the following Java code:

class TryCatch {
	static int edgecase() {
		try {
			System.out.println("Inside Try");
			return 0;

		} catch (Exception e) {
			System.out.println("Inside catch");
			return 1;
		}
		finally {
			return 42;
		}
	}

	static int edgecase2() {
		try {
			System.out.println("Inside Try");
			throw new Exception("exception");
		} catch (Exception e) {
			System.out.println("Inside catch");
			return 1;
		}
		finally {
			return 42;
		}
	}

	public static void main(String args[]) {
		int ret1 = edgecase();
		System.out.println(ret1);
		int ret2 = edgecase2();
		System.out.println(ret2);
	}
}

It uses finally blocks inside try catch statements where there are multiple returns.

However, the Java compiler always, in every code path possible, inlines the finally block's statements so it is always run no matter what branch is taken.

Hence the usual thinking that the return value will be one from the try or catch blocks is wrong.

Answers

Inside Try
ret1 will be 42

Inside Try
Inside Catch
ret2 will also be 42

As stated above, finally is in-lined before the try or catch blocks exit out and its done for every branch it takes, no matter how many nested try-catch or if-elses are there.

Hence before the final return from each, its actually getting preceded by the return 42 from finally block.