finally是可选的。
finally中声明的是一定会被执行的代码,即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。
像数据库连接,输入输出流,网络编程Socket等资源,JVM是不能自动回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中(以防资源释放操作受到上述catch等语句的干扰)
try-catch-finally结构可以嵌套
package 异常处理;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Test;
public class FinallyTest {
@Test
public void test2() {
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
int data = fis.read();
while (data != -1) {
System.out.print((char) data);
data = fis.read();
}
fis.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//public void test1() {
// try {
// int a=10;
// int b=0;
// System.out.println(a/b);
// }
// catch (ArithmeticException e) {
// e.printStackTrace();// TODO: handle exception
// }
// catch (Exception e) {
// e.printStackTrace();
// // TODO: handle exception
// }
// System.out.println("666");
finally {
System.out.println("结束");
}
}
}