finally的用法

finally至關於在return前插入finally的代碼塊(void的方法,系統會默認加上return;),可是其是臨時獨立的java

public class Test
{
	public static void main(String[] args)
	{
		System.out.println(getValue());
	}

	public static int getValue()
	{
		int i = 0;
		try
		{
			System.out.println("try block");
			i=4;
			return i;
		} finally
		{
			System.out.println("finally block");
			++i;
		}
	}
}

返回spa

try block
finally block
4


如在finally里加入return,則提早返回了,也即返回finally裏returncode

public class Test
{
	public static void main(String[] args)
	{
		System.out.println(getValue());
	}

	public static int getValue()
	{
		int i = 0;
		try
		{
			System.out.println("try block");
			i=4;
			return i;
		} finally
		{
			System.out.println("finally block");
			++i;
			return i;
		}
	}
}

返回get

try block
finally block
5
相關文章
相關標籤/搜索