[Java] try catch finally注意点

try catch finaly 注意点

1.finaly块中有return语句

1.1 有异常出现的场景

示例程序:

public static void main(String[] args) {
    System.out.println(throwException());
}
public static int throwException() {
    try {
        int i = 1 / 0;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("catch块抛出异常");
    } finally {
        System.out.println("finally 块");
        return 0;
    }
}

运行结果:
image
在这种情况下,finally块中的return 0;会导致catch块中的异常没有正常抛出。

若不想异常无正常抛出的话,应该将return 0;放置在try catch finally块外。代码如下:

public static int throwException() {
    try {
        int i = 1 / 0;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("catch块抛出异常");
    } finally {
        System.out.println("finally 块");
    }
    return 0;
}

运行结果:
image
这样catch块中的异常就会正常抛出。



1.2 finally块赋值后返回结果

示例代码:

public static int throwException() {
    int result;
    try {
        result = 1;
        return result;
    } catch (Exception e) {
        result = 2;
        return result;
    } finally {
        result = 3;
        return result;
    }
}

运行结果:
image

这种情况下finally块中对result赋值后返回,就会影响try块中对result赋值的结果。

若发生异常:

public static int throwException() {
    int result;
    try {
        result = 1;
        int i = 1 / 0; // 模拟异常
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        result = 2;
        return result;
    } finally {
        result = 3;
        return result;
    }
}

运行结果:
image

出现异常,catch块中的赋值以后返回,最终返回的还是finally块赋值的结果。
总结:无论是try块还是catch块return的结果,都会被finally块return结果覆盖。

posted @ 2023-06-01 13:38  Yorkey  阅读(15)  评论(0)    收藏  举报