---
title: "java面试之finally用法"
author: "xiaomogui"
date: "2010-11-15T23:56:08Z"
tags: []
categories: ["编程语言"]
slug: "java-finally"
draft: false
lastmod: "2010-11-15T23:56:08Z"
id: 812317
url: "https://xiaomogui.iteye.com/blog/812317"
---

```
public class Test1 {

	public static void main(String[] args) {
		System.out.println(Test1.test()); // 结果是打印1
	}

	public static int test() {
		int x = 1;
		try {
			return x;
		} finally {
			x = 7;
		}
	}
}
```

 

   上面的结果打印的是1。为什么？

   首先看一下finally的特性： finally 块必须放在 try 或 try/catch 块的后面，不能单独使用。不可能退出 try 块而不执行其 finally 块。如果 finally 块存在，则它总会执行。

   当然也有特殊情况，如果在try块中执行System.exit(0); 语句，则程序终止而不执行finally。还有一种方法就是在执行try块的时候，断掉电源。。。

  执行的过程大体是这样的：

  int x = 1; // 此时x的值为1

  return x; // 此时x的值为1，当执行到这里的时候发现try块后面有finally块。则先把x的值（此时是1）放到一个临时变量里面，假设 y=1;

  x = 7;  // 执行到这里时 x为7。此句执行完成后，再执行return语句，直接return y； y存放的值为1。所以返回1。