[关闭]
@TryLoveCatch 2022-04-19T09:28:51.000000Z 字数 1779 阅读 409

Java知识体系之异常

Java知识体系


Java 异常类层次结构图概览 :

一些问题

Exception和Error有什么区别?

Exception和Error都是继承了Throwable类,在Java中只有Throwable类型的实例才可以被抛出(throw)或者捕获(catch),它是异常处理机制的基本组成类型。

Checked Exception 和 Unchecked Exception 有什么区别?

Exception又分为可检查(checked)异常和不检查(unchecked)异常。

finally 语句块可以使用 return吗?

可以,但是不建议。
不要在 finally 语句块中使用 return! 当 try 语句和 finally 语句中都有 return 语句时,try 语句块中的 return 语句会被忽略。

  1. public static int f(int value) {
  2. try {
  3. return value * value;
  4. } finally {
  5. if (value == 2) {
  6. return 0;
  7. }
  8. }
  9. }
  10. public static void main(String[] args) {
  11. System.out.println(f(2)); // 0
  12. }

finally 中的代码一定会执行吗?

不一定的!在某些情况下,finally 中的代码不会被执行。

就比如说 finally 之前虚拟机被终止运行的话,finally 中的代码就不会被执行。

  1. try {
  2. System.out.println("Try to do something");
  3. throw new RuntimeException("RuntimeException");
  4. } catch (Exception e) {
  5. System.out.println("Catch Exception -> " + e.getMessage());
  6. // 终止当前正在运行的Java虚拟机
  7. System.exit(1);
  8. } finally {
  9. System.out.println("Finally");
  10. }
  11. // 输出
  12. Try to do something
  13. Catch Exception -> RuntimeException

参考

https://javaguide.cn/java/basis/java-basic-questions-03.html#%E5%BC%82%E5%B8%B8

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注