1. 程式人生 > >Java中try catch finally 中有異常和return時處理先後

Java中try catch finally 中有異常和return時處理先後

public class TestDemo {
	private static String output = "";

	public static void foo(int i) {
		try {
			if (i == 1) {
				throw new Exception();
			}
		} catch (Exception e) {
			output += "2";
			return;
		} finally {
			output += "3";
		}
		output += "4";
	}

	public static void main(String[] args) {
		foo(0);
		foo(1);
		System.out.println(output);
	}
}

如上面的程式碼段

main方法中foo(0)執行時,會執行finally和最後的程式碼段

main方法中foo(1)執行時,因為i=1,所以走異常程式碼,catch塊捕捉到了後,執行catch裡的程式碼,return先不執行,執行完finally之後再執行return;

總結如下:

try catch finally執行順序
                                                                          無
try塊有異常-->catch程式碼塊return關鍵字——————>執行catch塊程式碼-->執行finally
                        |
                        |有
                        |_______

執行catch塊return前面的程式碼-->執行finally-->執行catch塊中的return