导入
错误与异常(orientation)
区分关键系统故障(Errors)和可管理的应用程序错误(Exceptions),以确定我们能够修复的问题,以及必须接受的问题。
1public class StackOverflowExample { 2 public static void main(String[] args) { 3 // 我们调用递归方法以启动无限循环 4 causeOverflow(); 5 } 6 7 public static void causeOverflow() { 8 // 此方法在没有任何停止条件的情况下自我调用 9 causeOverflow(); 10 } 11}
1public class ExceptionExample { 2 public static void main(String[] args) { 3 int numerator = 100; 4 int denominator = 0; 5 6 // 这行代码导致运行时中止此特定线程, 7 // 因为整数除以零是未定义的。 8 int result = numerator / denominator; 9 10 System.out.println("Result: " + result); 11 } 12}
表格
| Feature | Error | Exception |
|---|---|---|
| Origin | 大多来自 JVM 或环境问题。 | 大多来自应用逻辑或外部资源。 |
| Recoverability | 不可恢复;程序应终止。 | 可恢复;程序可以捕获并处理。 |
| Handling | 不应被捕获或处理。 | 应尽可能被捕获并解决。 |
| Examples | OutOfMemoryError, StackOverflowError. | NullPointerException, ArithmeticException. |