ITeye博客

finally结构的注意点(一)

codecook · 2010-08-08 10:52 · Java基础 · 编程语言 · Markdown

我们知道,try-catch-finally结构和try-finally结构是用来捕获异常的典型结构。 而finally结构的作用,通常是在catch结构中抛出异常时做一些清理工作(如释放资源)。 然而有3个典型的问题,可能会影响我们对finally作用的判断。

第一个问题:如果在catch结构中抛出异常,finally结构是否会被执行? 代码如下:


	/**
	 * 测试:如果在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中抛出的异常)

第二个问题:如果在finally结构中抛出异常,那这个异常会不会覆盖try-catch结构中抛出的异常? 代码如下:


	/**
	 * 测试:如果在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结构中抛出的异常。

第三个问题:如果在finally结构中有return语句,那这个返回值会不会覆盖try-catch结构中的返回值? 代码如下:


	/**
	 * 测试:如果在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除了做一些清理工作外,如果运用不当,也是会产生副作用的。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。