try catch finally

try catch finally

try  和 catch  只会执行一个,没异常执行try,有异常执行 catch、

finally是一定会执行的、、、

然而恶心的情况来了、当有了return:

分8种情况来讨论:

1、基本类型      非基本类型     try:return         finally:return

public class Mytry {
	public static void main(String[] args) {
		int i=test();//基本类型
		System.out.println("基本型------"+i);//基本型------2
		String j=test1();//非基本类型
		System.out.println("非基本型------"+j);//非基本型------
	}

	private static  String test1() {
		String x="hello";
		try {
			System.out.println("A---------"+x);//A---------hello
			x=x+"world";
			System.out.println("B---------"+x);//B---------helloworld
			return x;
		} catch (Exception e) {
			
		}
		finally {
			System.out.println("C---------"+x);//C---------helloworld
			x="";
			System.out.println("D---------"+x);//D---------
			return x;
		}
	}

	@SuppressWarnings("finally")
	private static int test() {
		int x=0;
		try {
			System.out.println("A_________"+x);//A_________0
			x++;
			System.out.println("B_________"+x);//B_________1
			return x;
		} catch (Exception e) {
			
		}
		finally {
			System.out.println("C________"+x);//C________1
			x++;
			System.out.println("D________"+x);//D________2
			return x;
		}
	}
}
结果:

A_________0
B_________1
C________1
D________2
基本型------2
A---------hello
B---------helloworld
C---------helloworld
D---------
非基本型------

结果:先执行try里面的所有语句,唯独return不执行,等执行完finally再回过去执行return,可是finally里面已经return了,所以直接返回finally里面的东西;

2、基本类型      非基本类型     try:return         finally:NO return

public class Mytry {
	public static void main(String[] args) {
		int i=test();//基本类型
		System.out.println("基本型------"+i);//基本型------1
		String j=test1();//非基本类型
		System.out.println("非基本型------"+j);//非基本型------helloworld
	}

	private static  String test1() {
		String x="hello";
		try {
			System.out.println("A---------"+x);//A---------hello
			x=x+"world";
			System.out.println("B---------"+x);//B---------helloworld
			return x;
		} catch (Exception e) {
			
		}
		finally {
			System.out.println("C---------"+x);//C---------helloworld
			x="";
			System.out.println("D---------"+x);//D---------
		}
		return "xxxxxx";
	}

	@SuppressWarnings("finally")
	private static int test() {
		int x=0;
		try {
			System.out.println("A_________"+x);//A_________0
			x++;
			System.out.println("B_________"+x);//B_________1
			return x;
		} catch (Exception e) {
			
		}
		finally {
			System.out.println("C________"+x);//C________1
			x++;
			System.out.println("D________"+x);//D________2
		}
		return 100;
	}
}
结果:

A_________0
B_________1
C________1
D________2
基本型------1
A---------hello
B---------helloworld
C---------helloworld
D---------
非基本型------helloworld
从结果上看:不管finally里面执行了什么,均不影响try里面的return的结果




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值