Break and continue statements will stop exception flow

As it is said in The Java Language Specification (http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.15):
The preceding descriptions say “attempts to transfer control” rather than just “transfers control” because if there are any try statements within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.
Let’s look into next example:

public class Test {
	private static void test() throws Exception {
		for (int i = 0; i < 3; i++) {
			try {
				throw new Exception("Exception text");
			} finally {
				System.out.println("Finally exception " + i);
				continue;
			}
		}
		System.out.println("Impossible");
	}

	public static void main(String[] args) throws Exception {
		test();
		System.out.println("Impossible 2");
	}
}

will produce output:

Finally exception 0
Finally exception 1
Finally exception 2
Impossible
Impossible 2

So, be extremely careful with your breaks!

Advertisements

Author: Artem's Blog

Working on software and more...

1 thought on “Break and continue statements will stop exception flow”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s