public class TestStream {
public static void main(String[] args) {
FileInputStream in = null;
try {
in = new FileInputStream("a.txt");
in.read();
//in.close 不能放在这,如果读取出现异常就不会执行这一步
所以放在finally中,但是放在finally中方法调用会出现问题,
要设置初始值 FileInputStream in = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
//null.close会发生空指针异常,所以要进行非空判断
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//第二种方式内部会关流
try (FileInputStream fin = new FileInputStream("a.txt")) {
in.read();
} catch (IOException e) {
}
}
}
IO 异常处理的两种方式
最新推荐文章于 2024-04-25 20:18:16 发布