try catch 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 "";
}

输出:

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语句

还需要注意return语句返回的为基本类型的值或为引用类型的地址

先看下基本类型的返回,观察以下代码,预测输出

public static void main(String[] args) {
    System.out.println(test());
}

public static int test() {
    int i = 0;
    try {
        i++;
        return i;
    } catch (Exception e) {
        i++;
        return i;
    } finally {
        i++;
    }
}

输出:

Connected to the target VM, address: '127.0.0.1:62094', transport: 'socket'
1
Disconnected from the target VM, address: '127.0.0.1:62094', transport: 'socket'

Process finished with exit code 0

执行流程:
image.png

再来看看引用类型的返回:

public static void main(String[] args) {
    System.out.println(test20());
}
public static String test20() {
    String s = "";
    try {
        s = "============";
        return s;
    } catch (Exception e) {
        s = "++++++++++++";
        return s;
    } finally {
        s = "-------------";
    }
}

输出:

Connected to the target VM, address: '127.0.0.1:52461', transport: 'socket'
============
Disconnected from the target VM, address: '127.0.0.1:52461', transport: 'socket'

Process finished with exit code 0

image.png

评论

暂无评论