关于return和finally

本来return和finally也不是个事。之前看虚拟机运行原理的时候就了解过。但是最近被人问起的时候,缺没有说清楚。所以整理一下记录下来。
1.如果返回的是个对象,finally里的的代码,可以改变对象内部的状态。
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) throws Exception {
		Test t = new Test();
		System.out.println(t.check());
	}

	public List<String> check() throws Exception {
		List<String> name = new ArrayList<String>();
		name.add("phl");
		try {
			System.out.println("try");
			return name;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("finally");
			name.add("piaohailin");
			for (int i = 0; i < 3; i++) {
				System.out.println("time:" + (i + 1) * 300);
				Thread.sleep(300);
			}
		}
		System.out.println("return");
		name.add("return");
		return name;
	}
}

输出
try
finally
time:300
time:600
time:900
[phl, piaohailin]

2.finally里面的赋值,不会影响返回结果
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) throws Exception {
		Test t = new Test();
		System.out.println(t.check());
	}

	public String check() throws Exception {
		String name = "phl";
		try {
			System.out.println("try");
			return name;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("finally");
			name = "piaohailin";
			for (int i = 0; i < 3; i++) {
				System.out.println("time:" + (i + 1) * 300);
				Thread.sleep(300);
			}
		}
		System.out.println("return");
		name = "return";
		return name;
	}
}

输出
try
finally
time:300
time:600
time:900
phl

3.finally里带有return方法,则此return会覆盖try里面的return
//warnning finally block does not complete normally
一般不这么用,因为有警告信息,不够优雅
package com.chinaso.phl;

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) throws Exception {
		Test t = new Test();
		System.out.println(t.check2());
	}

	public String check2() throws Exception {
		String name = "phl";
		try {
			System.out.println("try");
			return name;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("finally");
			name = "piaohailin";
			for (int i = 0; i < 3; i++) {
				System.out.println("time:" + (i + 1) * 300);
				Thread.sleep(300);
			}
			return name;
		}
	}
}

输出
try
finally
time:300
time:600
time:900
piaohailin

你可能感兴趣的:(finally)