try-catch-finally中finally的理解与使用

try-catch-finally中finally的理解与使用

package com.yichang.bean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/*
* try-catch-finally结构中finally的使用
*  ①finally在此结构中是可选的
*  ②finally中的代码是一定会被执行的,即使catch中又出现异常、try中有return语句、catch
*    中有return语句等情况
*  ③什么时候需要把代码写到finally中
*    像输入输出流、数据库连接、网络编程Socket等资源,JVM不能自动的回收,需要我们手动的进行
*    资源的释放,此时的资源释放,就需要写在finally语句中
*
* */
public class Finally {
    public static void main(String[] args) {
        Finally f = new Finally();
        f.test2();
    }
    public void test(){
        try{
            int a = 10;
            int b = 0;
            System.out.println(a/b);
        }catch(ArithmeticException e){
//            e.printStackTrace();
            int[] arr = new int[10];
            System.out.println(arr[10]);//这里的数组索引超出范围,应该退出整个程序,但是一定会执行finally
        }finally{
            System.out.println("finally中的代码一定会被执行");
        }
    }
    public int test2(){
        try{
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            return 2;
        }finally{
            System.out.println("此语句一定会被执行");
        }
    }
    public void test3(){
        //
        FileInputStream fis = null;
        try{
            File file =new File("hello.txt");
            //本来应该是FileInputStream fis = new FileInputStream(file);
            //但是此处把其声明在外面,且赋值为null,这样下面就可以使用
            fis = new FileInputStream(file);
            int data = fis.read();
            while(data!=-1){
                System.out.println((char)data);
                data = fis.read();
            }
        } catch(IOException e){
            e.printStackTrace();
        } finally{
            //由此可见,此结构也可以嵌套
            try{
                if (fis != null)
                    //fis.close();如果放在前面,则其不一定被执行,可能会被忽略
                    //所以有必要放在finally中
                    fis.close();
            }catch(IOException e){
                e.printStackTrace();
            }

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值