首页 > 解决方案 > 最终覆盖异常

问题描述

我知道从最终块返回的值总是覆盖返回的任何内容,但它应该覆盖或抑制抛出的异常吗?

public static String callme() throws Exception {
    try {
        throw new Exception();
    } catch (Exception e) {
        System.out.println("inside the catch block");
        throw e;
    } finally {
        System.out.println("Inside finally");
        return "returned from finally";
    }

}

public static void main(String[] args) {
    try {
        System.out.println(callme());
    } catch (Exception e) {
        System.out.println("something is caught");
    }
}

预期输出 -

inside the catch block
Inside finally
returned from finally
something is caught

现实 -

inside the catch block
Inside finally
returned from finally

我想问

  1. 为什么会这样?

  2. 如果它发生了,那不是很糟糕,因为调用方法不会知道抛出的异常

标签: javaexceptiontry-catch

解决方案


推荐阅读