Java异常处理-try-catch-finally中finally的使用

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

/**
 *
 * try-catch-finally中finally的使用
 *
 *
 * 1.finally是可选的
 *2.finally中声明的是一定会被执行的代码,即使catch中又出现异常了,try中有return语句,catch中也有return语句等情况。
 *3.哪些是必须要执行的代码
 *  像数据库连接,输入输出流,网络编程Socker等资源,JVM是不能自动回收的,我们需要自己手动的进行资源的释放,此时的资源
 *  释放,就要声明在finally中
 *
 *
 * @author orz
 */
public class FinallyTest {
    public static void main(String[] args) {
//        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[11]);
//        }
////       System.out.println("我好帅啊~~");
//        finally {
//            System.out.println("我好帅啊~~");
//        }


        FileInputStream fis=null;
        try {
            File file = new File("hello.txt");
            fis = new FileInputStream(file);
            int data = fis.read();
            while (data != -1) {
                System.out.println((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();
            }

        }

    }
}

猜你喜欢

转载自www.cnblogs.com/orzjiangxiaoyu/p/13388139.html