Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在finally块中,我可以告诉您抛出了什么异常吗?_Java_Exception_Try Catch Finally - Fatal编程技术网

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

Java 在finally块中,我可以告诉您抛出了什么异常吗?,java,exception,try-catch-finally,Java,Exception,Try Catch Finally,在finally块中,我能告诉抛出了什么异常吗 我知道,如果抛出异常,我们可以在finally块中进行验证。我无法想象这样做会是明智的,但您可以尝试以下方法: class Main { public static void throwsException() throws Exception { throw new Exception(); } public static void main(String[] args) { Exce

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


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

我无法想象这样做会是明智的,但您可以尝试以下方法:

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);
        }
    }
}

catchblock和finally是两个不同的范围。catch块中捕获的异常对finally块不可见。您可以使用Alexander answer在finally块中打印异常。

您可以在与
try
相同的范围内拥有一个变量,并将其设置为
catch
中引发的异常。我不认为这有一个内置的机制,如果你需要的话,可能会有人认为你的设计是错误的。请注意,显然,当代码进入
finally
时,可能没有引发异常。您不需要知道。此时,您只关心清理。任何异常都已被处理。您不应该担心
finally
块中的异常,这就是
catch
块的作用,您需要做什么?正如其他人所说,您可以在
catch
中处理异常,
最后
用于清理任何资源,而不是处理异常。应该不必考虑是否在代码中抛出异常。最后,<代码>。