Artem's blog

March 24, 2008

Break and continue statements will stop exception flow

Filed under: Software — Tags: , , , , — Artem @ 3:59 AM

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!

 
 

You need to log in to vote

The blog owner requires users to be logged in to be able to vote for this post.

Alternatively, if you do not have an account yet you can create one here.

Powered by Vote It Up

Powered by WordPress