---
title: "总结一下 try...catch...finally 在一个方法作用域内的使用"
author: "nello"
date: "2014-03-31T23:30:14Z"
tags: []
categories: ["编程语言"]
slug: "try-catch-finally"
draft: false
lastmod: "2014-03-31T23:34:18Z"
id: 2039068
url: "https://technique-digest.iteye.com/blog/2039068"
---

好像在 java 面试的时候关于异常的内容都是必问的东西，这里就不介绍有关异常的接口和主要的类了，也不讨论性能问题，就简单总结下 try...catch...finally 在一个方法作用域内的使用。

 

1，一个方法内可以有多个 try...catch...finally 语句块，还可以彼此嵌套；

```
public static String TestTry() {
		try {
			try {
				
			} catch (Exception e) {
				// TODO: handle exception
			} finally {
				
			}
		} catch (Exception e) {
			try {
				
			} catch (Exception e2) {
				// TODO: handle exception
			} finally {
				
			}
		} finally {
			try {
				
			} catch (Exception e2) {
				// TODO: handle exception
			} finally {
				
			}
		}
		
		try {
			
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			
		}
		return "return"; // 这里必须写
	}
```

 

2，如果一个有返回值的方法内有多个 try...catch...finally 语句块，return 语句要么写在任意一个 try...catch 内，要么写在方法的最后，否则编译无法通过，如果 return 语句写在方法的最后，那么以上 try...catch...finally 语句中的 每一个 finally 块内的代码都将会执行；

```
public static String TestTry2() {
		try {
			//return "hello1";
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			System.out.println("final1");
		}
		
		try {
			//return "hello2";
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			System.out.println("final2");
		}
		
		return "hello3"; // 这里必须写
	}
```

 

3，无论方法内是否发生异常（jvm 可以处理的异常），finally 块内的代码都将会执行。

```
public static String TestTry3() {
		try {
			return "hello";
			//return String.valueOf(9/0);
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			System.out.println("final");
		}
		return "re"; // 这里必须写
	}
```