Try-Catch-Finally

1、try-catch-finall验证分析

1.如果try语句中有return语句,返回当前try中变量此时对应的值,此后对变量做任何修改,不影响try中return的值。

2.如果finally语句中有return语句,try或者catch中返回语句忽略。

3.如果finally抛出异常,整个try-catch-finall抛出异常。

2、使用注意

1.尽量在try或者catch中使用return语句。通过finally中达到对try或者catch返回值修改不可靠。

2.finally中尽量避免使用return,因为会屏蔽try、catch中的异常信息。

3.finally中避免再次抛出异常,否者整个包含try语句块的方法都会抛出异常,并且屏蔽掉try-catch中的异常。

3、示例代码

public class TryCatchFinally {

	public static void main(String[] args) {
		System.out.println(tryCatchFinally_01());
		System.out.println(tryCatchFinally_02());
		System.out.println(tryCatchFinally_03());
		System.out.println(tryCatchFinally_04());
		System.out.println(tryCatchFinally_05());
		System.out.println(tryCatchFinally_06());
		System.out.println(tryCatchFinally_07());
	}
	
	public static String tryCatchFinally_01() {
		String t = "";
		try {
			t = "try";
			return t;
		} catch (Exception e) {
			t = "catch";
			return t;
		} finally {
			t = "finally";
		}
	}
	
	@SuppressWarnings("finally")
	public static String tryCatchFinally_02() {
		String t = "";
		try {
			t = "try";
			return t;
		} catch (Exception e) {
			t = "catch";
			return t;
		} finally {
			t = "finally";
			return t;
		}
	}
	
	public static String tryCatchFinally_03() {
		String t = "";
		try {
			t = "try";
			Integer.valueOf(null);
			return t;
		} catch (Exception e) {
			t = "catch";
			return t;
		} finally {
			t = "finally";
		}
	}
	
	@SuppressWarnings("finally")
	public static String tryCatchFinally_04() {
		String t = "";
		try {
			t = "try";
			Integer.valueOf(null);
			return t;
		} catch (Exception e) {
			t = "catch";
			return t;
		} finally {
			t = "finally";
			return t;
		}
	}
	
	public static String tryCatchFinally_05() {
		String t = "";
		try {
			t = "try";
			Integer.valueOf(null);
			return t;
		} catch (Exception e) {
			t = "catch";
			Integer.valueOf(null);
			return t;
		} finally {
			t = "finally";
		}
	}
	
	@SuppressWarnings("finally")
	public static String tryCatchFinally_06() {
		String t = "";
		try {
			t = "try";
			Integer.valueOf(null);
			return t;
		} catch (Exception e) {
			t = "catch";
			Integer.valueOf(null);
			return t;
		} finally {
			t = "finally";
			return t;
		}
	}
	
	@SuppressWarnings("finally")
	public static String tryCatchFinally_07() {
		String t = "";
		try {
			t = "try";
			Integer.valueOf(null);
			return t;
		} catch (Exception e) {
			t = "catch";
			Integer.valueOf(null);
			return t;
		} finally {
			t = "finally";
			Integer.valueOf(null);
			return t;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值