Java基础之JDK7关于异常的新特性try()的使用

part1  为什么在try后面括号中出现FileNotFoundExecption 但是需要捕获的是IOException而不是FileNotFoundException?

代码如下
 

try (FileInputStream is = new FileInputStream("d:/temp/tt.txt");){

		} catch (FileNotFoundException e) { // 为什么需要捕获的是IOException而不是FileNotFoundException?
			System.out.println("执行了catch部分");
//			((Throwable) e).printStackTrace();
		} finally {
			System.out.println("执行了finally部分");
		}

代码报错:Unhandled exception type IOException thrown by automatic close() invocation on is

从报错的内容上大致我们可以得知,is自动调用close()从而抛出了未解决的IOException异常类型

原因是 Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。带有resources的try语句声明一个或多个resources。resources是在程序结束后必须关闭的对象。try-with-resources语句确保在语句末尾关闭每个resources。任何实现java.lang.AutoCloseable,包括实现了java.io.Closeable的类,都可以作为resources使用。      也就是try()括号中的代码自动实现了 close()  但是close()会引起 IOException  所以下面catch需要追加IOException.

追加后IOEexception后  由于FIleNotFoundException是 IOException的子类  所以 只需要IOException即可满足。

猜你喜欢

转载自blog.csdn.net/Hurricane_m/article/details/89185856