在finally块中,我可以告诉抛出了什么异常吗?

时间:2017-03-10 01:22:29

标签: java exception try-catch-finally

在finally块中,我可以告诉抛出了什么异常吗?

我理解,如果抛出异常,我们可以在finally块中进行验证。

2 个答案:

答案 0 :(得分:6)

我无法想象这种情况应该是明智的做法,但你可以尝试这样的事情:

class Main {
    public static void throwsException() throws Exception {
        throw new Exception();  
    }

    public static void main(String[] args) {
        Exception caughtException = null;

        try {
            throwsException();
        }
        catch (Exception e) {
            caughtException = e;
            e.printStackTrace();
        }
        finally {
            System.out.println(caughtException);
        }
    }
}

答案 1 :(得分:0)

捕获块和最终是两个不同的范围。 最终块无法看到 catch 块中捕获的异常。您可以使用Alexander答案在finally块中打印异常。