try_catch_finally和try_with_Resource

try_catch_finally

package JavaSE.异常;

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

public class Try_catch_finally {

    public static void main(String[] args) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(System.getProperty("user.dir") + "\\尚学堂练习\\src\\main\\java\\JavaSE\\File类\\TestFile.java");
            char a = (char) fileReader.read();
            System.out.println(a);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

try_with_Resource

ry_with_resource可以自动实现AutoCloseable接口可以自动关闭close()资源

package JavaSE.异常;

import java.io.FileReader;

public class Try_with_resource {
    public static void main(String[] args) {
       // try_with_resource可以自动实现AutoCloseable接口可以自动关闭close()资源
        try (FileReader fileReader = new FileReader(System.getProperty("user.dir")
                + "\\尚学堂练习\\src\\main\\java\\JavaSE\\File类\\TestFile.java");
        ) {
            char a = (char) fileReader.read();
            System.out.println(a);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/wqr111/article/details/118380963