一、finally 的使用说明
1、finally 的理解
1、我们将一定要被执行的代码声明在 finally 结构中。 2、更深刻的理解:无论 try 中或者 catch 中是否存在未被处理的异常,无论 try 中或 catch 中是否存在 return 语句等,finally 中声明的语句都一定要被执行。 3、finally 语句和 catch 语句是可选的,但是 finally 不能单独使用。 4、try-catch 可以嵌套使用。
2、什么样的代码我们一定要声明在 finally 中呢?
我们在开发中,有一些资源,比如:输入流、输出流、数据库连接、socket 连接等资源,在使用完以后,必须显式的进行关闭操作,否则,GC 不会自动的回收这些资源。进而导致内存泄漏。 为了保证这些资源在使用完之后,不管是否出现了未被处理的异常的情况下,这些资源能被关闭。我们必须将这些操作声明在 finally 中。
package trycatchfinally;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FinallyTest {
public static void main(String[] args) {
FinallyTest f = new FinallyTest();
f.test1();
}
public void test1() {
try {
String str = "123";
str = "abc";
int i = Integer.parseInt(str);
System.out.println(i);
} (NumberFormatException e) {
e.printStackTrace();
System.out.println( / );
} {
System.out.println();
}
}
{
;
{
();
fis = (file);
fis.read();
(data != -) {
System.out.println(() data);
data = fis.read();
}
} (FileNotFoundException e) {
e.printStackTrace();
} (IOException e) {
e.printStackTrace();
} {
{
(fis != ) {
fis.close();
}
} (IOException e) {
e.printStackTrace();
}
}
}
}


