• Day63-每日一道Java面试题-try-catch-finally 如何使用?


    • try块 : 用于捕获异常。其后可接零个或多个 catch 块,如果没有 catch 块,则必须跟一个 finally 块。
    • catch块 : 用于处理 try 捕获到的异常。
    • finally 块 : 无论是否捕获或处理异常,finally 块里的语句都会被执行。当在 try 块或 catch 块中遇到 - return 语句时,finally 语句块将在方法返回之前被执行。
      代码示例:
    try {
        System.out.println("Try to do something");
        throw new RuntimeException("RuntimeException");
    } catch (Exception e) {
        System.out.println("Catch Exception -> " + e.getMessage());
    } finally {
        System.out.println("Finally");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    输出:

    Try to do something
    Catch Exception -> RuntimeException
    Finally
    
    • 1
    • 2
    • 3

    注意:不要在 finally 语句块中使用 return! 当 try 语句和 finally 语句中都有 return 语句时,try 语句块中的 return 语句会被忽略。这是因为 try 语句中的 return 返回值会先被暂存在一个本地变量中,当执行到 finally 语句中的 return 之后,这个本地变量的值就变为了 finally 语句中的 return 返回值。

    jvm 官方文档中有明确提到:

    If the try clause executes a return, the compiled code does the
    following:

    Saves the return value (if any) in a local variable. Executes a jsr to
    the code for the finally clause. Upon return from the finally clause,
    returns the value saved in the local variable.

    代码示例:

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

    输出:

    0
    
    • 1

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

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

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

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

    输出:

    Try to do something
    Catch Exception -> RuntimeException
    
    • 1
    • 2

    另外,在以下 2 种特殊情况下,finally 块的代码也不会被执行:

    1.程序所在的线程死亡。
    2.关闭 CPU。

  • 相关阅读:
    jackson反序列化get空值null抛异常的问题处理方案
    已经刷新了四大公开数据集纪录?吃一记新ReID数据集安利!
    linux 发行版中在容器内访问热插拔 U 盘的分区内容
    【STM32】两个版本MDK搭建和三种调试器的使用
    ++和*(解引用)的优先级
    万卷书 - 书单整理 [01]
    吃透Chisel语言.28.Chisel进阶之有限状态机(二)——Mealy状态机及与Moore状态机的对比
    Java Web(五)之 web核心(HTTP协议,Tomcat服务器,Servlet)
    Web Component-初识
    [数据集][目标检测]遥感图像游泳池检测数据集VOC+YOLO格式288张1类别
  • 原文地址:https://blog.csdn.net/Youmonster/article/details/126474994