package com.example.demo;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @Description 异常机制 try、catch、finally、return 执行顺序
* @Auther gf.x
* @Date 2020/4/6 19:40
*/
public class TryCatchTest {
public static void main(String[] args) {
//这样只声明变量 不初始化,fileReader变量在下面是无法使用的;因为fileReader变量是局部变量(局部变量既要声明又要初始化,然后才能使用)
//FileReader fileReader;
FileReader fileReader = null;
try {
//fileReader变量是个局部变量,只在try语句块有效;所以要想其他块也能用,就要在放在外面声明
//此行代码有可能会抛出 FileNotFoundException(文件找不到) 异常
fileReader = new FileReader("E:/test/child/a.txt"); //此处抛出异常,程序会依次寻找下面的catch块
char c = (char)fileReader.read();
char c2 = (char)fileReader.read();
System.out.println(c + c2); //195
System.out.println("" + c + c2); //ab
/*
} catch (IOException e) { //IOException是FileNotFoundException的父类
e.printStackTrace();
} catch (FileNotFoundException e) { //Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
e.printStackTrace();
}
*/
} catch (FileNotFoundException e) { //此处捕获一下上面抛出的异常
e.printStackTrace(); //捕获异常后 打印异常信息
} catch (IOException e) { //注意:IOException块与FileNotFoundException块不能交换位置
e.printStackTrace();
} finally {
try {
if (fileReader != null) {
fileReader.close(); //如果上面 new FileReader 时就抛异常的话,此处的fileReader就是null;这里就会抛空指针异常
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}