Exceptions
An exception is an object thrown when normal control flow is disrupted. Learn who throws, who catches, and which exceptions must be handled.Exception 是程序正常流程被打断时抛出的对象。你要知道什么时候 throw,谁 catch,以及 checked 和 unchecked 的区别。
The direction exceptions travel异常的流动方向
try {
readFile("data.txt");
} catch (IOException e) {
System.out.println("File read failed");
} finally {
closeResource();
}
throw: create and raise an exception.:创建并抛出异常。catch: handle a specific exception type.:处理某种异常。finally: run cleanup whether the operation succeeds or fails.:不管成功失败都执行,常用于释放资源。
Whether the compiler forces handling编译器会不会逼你处理
| Type类型 | Example例子 | Meaning怎么理解 |
|---|---|---|
| Checked exception | IOException | External failures; the compiler requires catch or throws.外部环境导致的失败,编译器要求 catch 或 throws。 |
| Unchecked exception | NullPointerException | Usually code bugs or invalid calls; not forced by the compiler.通常是代码 bug 或非法调用,不强制 catch。 |