Java Planet

O Javie i jej otoczeniu

try-catch-finally

Kolejne, ciekawe pytanie z JavaBlackbelt (lekko zmodyfikowany) dotyczące konstrukcji try/catch/finally
Warto zwrócić uwagę na trochę nieoczekiwane działanie w przypadku gdy w metodzie finally użyjemy return

public class TestException {

	public static void main(String[] args) {
		String s = "BIRD";

		try {
			String x = "DOG";
			throw new Exception();
		} catch (Exception e) {
			System.out.println("Catch block");
			s = "MOOSE";
		} finally {
			s = "GOAT";
			/*
			 * do zmiennej x nie mamy dostępu w bloku finally
			 * Ta linia powoduje błąd kompilacji
			 */
			// x = "FROG";
			System.out.println("Finnaly block");
		}
		System.out.println(s);
		/*
		 * Rezultat działania:
		 *
		 * Catch block
		 * Finnaly block
		 * GOAT
		 */
	}
}

A return statement is executed in the finally block, so the method returns and does not throw the exception.

	void method1() throws Exception {
		try {
			int a = 0;
			if (a == 0) {
				throw new Exception();
			}
		} finally {
			return;
		}
	}

Kolejny przykład z użyciem finnaly i zamknięciem w nim return

public class TestException2 {

	public static String getVal() {
		String s = "BIRD";
		try {
			return s;
		} finally {
			s = "GOAT";
			System.out.println("Finnaly block");
			// gdyby wykonać return s; mielibyśmy:
			/*
			 * Rezultat działania:
			 * Finnaly block
			 * Returned: GOAT
			 */
		}
	}

	/*
	 * Rezultat działania:
	 * Finnaly block
	 * Returned: BIRD
	 */
	public static void main(String[] args) {
		System.out.println("Returned: "+getVal());

	}
}

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

COMMENTS

No Comments

There are no comments posted yet. Be the first one!

Leave a Replay