Reputation: 352
In a finally block, can I tell what exception has been thrown?
I understand, that we can verify in a finally block if an exception had been thrown.
Upvotes: 2
Views: 1596
Reputation: 985
catch block and finally are 2 different scopes . The exception caught in the catch block is not visible to finally block. You can use the Alexander answer to print the exception in the finally block.
Upvotes: 0
Reputation: 63157
I can't envision a situation in which this would ever a sensible thing to do, but you can try something like this:
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);
}
}
}
Upvotes: 6