• 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。

  • 相关阅读:
    nios ii开发随笔
    软考初级网络管理员__网络单选题
    git的基本使用1
    静态HTML CSS个人网页作业源代码 (人物介绍)
    unity脚本的生命周期
    ensp无线WLAN和无缝漫游出现问题
    C语言:文件操作(2)
    Java 中线程池的 7 种创建方式!
    深入理解Java基本数据类型与引用数据类型
    这资源也太强了!8月版最新AI脚本插件合集来了
  • 原文地址:https://blog.csdn.net/Youmonster/article/details/126474994