[Java] try catch finally注意点

发布时间 2023-06-01 13:42:47作者: Yorkey

try catch finaly 注意点

finaly块中有return语句

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