Unchecked Exception
Unchecked exception 是指在编译时并不要求必须处理的异常。
Unchecked exception 包括 RuntimeException 和其子类,比如 NullPointerException、IndexOutOfBoundsException、ClassCastException 等。Unchecked exception 一般是由程序逻辑错误引起的,如除以零、数组越界、类型转换失败等。
Unchecked exception 不会导致程序的终止,只是在运行时抛出异常,并由调用者进行捕获处理。
Checked Exception
Checked exception 是指在编译时必须处理的异常。
Checked exception 包括 Exception 和其子类,比如 IOException、SQLException 等。Checked exception 一般是由外部因素导致的,如文件读写失败、网络连接失败等。
Checked exception 会导致程序的终止,因为调用者没有能力处理异常。
总结
Unchecked exception 一般用于程序逻辑错误,如除以零、数组越界、类型转换失败等。Checked exception 一般用于外部因素导致的错误,如文件读写失败、网络连接失败等。
在编写代码时,应该尽量处理 Checked exception,避免程序终止。对于 Unchecked exception,可以选择抛出异常或者捕获异常进行处理。