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

  • 相关阅读:
    Harmony Ble 蓝牙App (一)扫描
    java计算机毕业设计springboot+vue+elementUI永加乡精准扶贫信息管理系统
    [Arduino电子近源渗透] Night of 19 v1.2.0
    QT高阶-QSS样式表用法大全
    一个依赖解决 Spring Boot 反爬虫,防止接口盗刷
    Python+Django+Html网页前后端指纹信息识别
    项目绩效评估七宗罪
    CentOS 6服务器升级Git时, 下载依赖包失败,需配置国外Yum源
    S09-录入的数据快速分列
    外汇天眼:复制跟单交易:仍会是未来外汇交易发展的主流么?
  • 原文地址:https://blog.csdn.net/Youmonster/article/details/126474994