Java 在finally块中,我可以告诉您抛出了什么异常吗?
在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块中进行验证。我无法想象这样做会是明智的,但您可以尝试以下方法:
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
中处理异常,最后
用于清理任何资源,而不是处理异常。应该不必考虑是否在代码中抛出异常。最后,<代码>。