阅读背景:

[随记] try catch finally return 执行顺序

来源:互联网 

package com.s.example;

/**
 * 测试try cache finally 履行次序和return
 * @author jacksang
 *
 */
public class Test {

	public static void main(String[] args) {
		
		int i;
		
		i = firstOne();
		System.out.println(i);
		
		i = firstTwo();
		System.out.println(i);
	}
	
	/**
	 * 在try涌现异常finally涌现return是不是会履行
	 */
	public static int firstOne(){
		try {
			System.out.println("try"); 
			throw new RuntimeException();
		} catch(Exception e) {
			System.out.println("catch");
		} finally {
			System.out.println("finally");
			return 1;
		}
		return 2;
	}
	
	//履行次序
//	1. 打印"try"
//	2. 遇到throw RuntimeException
//	3. 捕获异常信息走catch,打印"catch"
//	4. 最后履行finally,并且返回1
//	5. main函数中输出1 (finally中包括return后外部return不履行)

	/**
	 * try中return会不会履行finally
	 */
	public static int firstTwo(){
		try {
			System.out.println("try"); 
			return 1;
		} catch(Exception e) {
			System.out.println("catch");
		} finally {
			System.out.println("finally");
		}
		return 2;
	}
	//履行次序
//	1. 打印"try"
//	2. 最后履行finally,并且返回1
//	3. main函数中输出1 (finally中包括return后外部return不履行)
	//注意如果在finally中包括return,将直接返回,try中return失效
	
}
 
 package com.s.example;

/**
 * 测试try cache finally




你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: