Java 语言的 Exception
定义:
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
类继承关系:
Object
--Throwable .............................. 鼻祖, 所有 exception 的祖先
----Error .................................... 程序外部问题, 无法预期, 不可恢复
----Exception ............................. 除 RuntimeException 外, 都可预期, 可恢复
------RuntimeException ............. 程序内部问题, 无法预期, 不可恢复
不可预期的 Error 和 RuntimeException 都是不强制需要 try 或 throws 声明捕获的.
除了 Error 和 RuntimeException, 及其之类之外, 都需要 try 或 throws 声明捕获, 包括 throw 的 Throwable.
Error 和 RuntimeException, 及其子类被认为是 unchecked exception, 其他被认为是 checked exception, checked exception 都必须被声明捕获.
除了 try-catch-finally 块之外, Java SE 7 引入了 try-with-resources 语句, 这种新的语句特别使用于可以 Closeable 的 resources. 凡是实现 java.io.Closeable 接口的对象, 都可以通过这种语句来自动 close resource;
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
br.readLine();
}
当然 try 后面的括号中可以 声明多个 resource, 用;分开就行.
同时, 它仍然还可以跟 catch, finally 块.
Java SE 7 还引入了下面的语句:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
一般的try语句, 必须有 catch 或者 finally 跟随, 但是 try-with-resource 语句之后, 就不必了.