---
title: "finally结构的注意点(一)"
author: "codecook"
date: "2010-08-08T10:52:40Z"
tags: []
categories: ["编程语言"]
slug: "finally"
draft: false
lastmod: "2010-08-08T20:56:22Z"
id: 731972
url: "https://codecook.iteye.com/blog/731972"
---

我们知道，try-catch-finally结构和try-finally结构是用来捕获异常的典型结构。
而finally结构的作用，通常是在catch结构中抛出异常时做一些清理工作(如释放资源)。
然而有3个典型的问题，可能会影响我们对finally作用的判断。

<span style="color:red">第一个问题：如果在catch结构中抛出异常，finally结构是否会被执行？</span>
代码如下：

```java

	/**
	 * 测试：如果在catch结构中抛出异常，finally结构是否会被执行。 结果：会被执行。
	 * 
	 * @throws Exception
	 */
	public static void testThrowExceptionInCatch() throws Exception {
		try {
			throw new Exception();
		} catch (Exception ex) {
			throw new Exception();
		} finally {
			System.out.println("finally");// execute this line;
		}
	}

```

通过执行testThrowExceptionInCatch()函数，我们知道，finally是会执行的。（catch结构也产生了副作用，抛出的异常会覆盖try中抛出的异常）

<span style="color:red">第二个问题：如果在finally结构中抛出异常，那这个异常会不会覆盖try-catch结构中抛出的异常？</span>
代码如下：

```java

	/**
	 * 测试：如果在finally结构中抛出异常，那这个异常会不会覆盖try-catch结构中抛出的异常。 结果：会覆盖。
	 * 
	 * @throws Exception
	 */
	public static void testThrowExceptionInFinally() throws Exception {
		try {
			throw new Exception();
		} catch (Exception ex) {
			throw new Exception();
		} finally {
			System.out.println("start finally");
			throw new Exception();
		}
	}

```

通过执行testThrowExceptionInFinally()函数，发现finally结构中抛出异常覆盖了try-catch结构中抛出的异常。

<span style="color:red">第三个问题：如果在finally结构中有return语句，那这个返回值会不会覆盖try-catch结构中的返回值？</span>
代码如下：

```java

	/**
	 * 测试：如果在finally结构中有return语句，那这个返回值会不会覆盖try-catch结构中的返回值。 结果：会覆盖。
	 * 
	 * @return
	 * @throws Exception
	 */
	public static int testReturnValueInFinally() throws Exception {
		try {
			return 1;
		} catch (Exception ex) {
			throw new Exception();
		} finally {
			System.out.println("finally");
			return 2;// 覆盖返回值
		}
	}

```

通过执行testReturnValueInFinally()函数，返回值为2，可见finally结构中的return语句覆盖了try-catch结构中的返回值。

可见，finally除了做一些清理工作外，如果运用不当，也是会产生副作用的。