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

猜你喜欢

转载自blog.csdn.net/zlpzlpzyd/article/details/83475642