一、finally介绍
1.finally是可选的
2.finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。
二、finally的使用
1.当catch中出现异常
代码如下(示例):
public void test1(){
try{
int a = 10;
int b = 0;
System.out.println(a / b);
}catch(ArithmeticException e){
e.printStackTrace();
//catch中出现异常
int[] arr = new int[10];
System.out.println(arr[10]);
}catch(Exception e){
e.printStackTrace();
}
// System.out.println("打印1");
finally{
System.out.println("打印2");
}
}
如果catch中出现异常,直接退出此方法,打印1就不能显示,但如果将打印1放在finnally中,即使catch中出现异常,仍然可以打印。
2.try中有return语句
代码如下(示例):
public void testMethod(){
int num = method();
System.out.println(num);
}
//try中有return语句
public int method(){
try{
int[] arr = new int[10];
System.out.println(arr[10]);
return 1;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
return 2;
}finally{
System.out.println("我一定会被执行");
return 3;
}
最终return的结果是3
3.手动进行资源的释放
代码如下(示例):
问题代码:
@Test
public void test2(){
try{
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
fis是一个输入输出流,不能被JVM自动回收,用fis.close()手动回收,但如果再close前出现异常,跳到catch语句中,fis.closed()就不能被执行到,所以需要用finally改进
改进:
public void test2(){
FileInputStream fis = null;
try {
File file = new File("hello1.txt");
fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样不管出不出现异常,finally中的代码是一定会执行的
总结
像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。