关于java:如果catch异常处理代码块中包含了return语句那么finally还会执行吗

运行以下代码

public static void main(String[] args) {
    System.out.println(test());
}
public static String test(){
    try {
        int t = 1 / 0;
        System.out.println("============");
    } catch (Exception e) {
        System.out.println("-------------");
        return "exception";
    } finally {
        System.out.println("++++++++++++");
    }
    return "";
}

输入:

D:\java1.8\jdk1.8.0_60\bin\java.exe ...
Connected to the target VM, address: '127.0.0.1:49697', transport: 'socket'
-------------
++++++++++++
exception
Disconnected from the target VM, address: '127.0.0.1:49697', transport: 'socket'

Process finished with exit code 0

论断:

  1. 依据输入后果能够看出即便catch代码块中蕴含return也同样会执行finally代码块中的内容
  2. finally代码块执行结束后会继续执行catch代码块中的return语句

    那么finally代码块中同样蕴含一个return语句又会怎么执行呢?

public static void main(String[] args) {
    System.out.println(test());
}
public static String test() {
    try {
        int t = 1 / 0;
        System.out.println("============");
    } catch (Exception e) {
        System.out.println("-------------");
        return "exception";
    } finally {
        System.out.println("++++++++++++");
        return "***************";
    }
}

输入:

Connected to the target VM, address: '127.0.0.1:49329', transport: 'socket'
-------------
++++++++++++
***************
Disconnected from the target VM, address: '127.0.0.1:49329', transport: 'socket'

Process finished with exit code 0

论断:
从运行后果中能够看出若finally代码块中蕴含了return语句则不会再去执行catch中的return语句

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理