I got this question by email. Posting it here and will answer in one minute.
email wrote:On page 307, it says that if an exception is thrown, then the finally block runs after the catch block. If no exception, then the finally block runs after the try block.
However, on page 312, there's a code snippet that looks like this:
Then on page 313, it says the finally block runs after the try block. The thing is, page 307 told me that the catch block has to be executed because the try block throws a Runtime Exception. I'm really confused about this contradiction. So why does the finally block run after the catch block? Is the catch block just ignored entirely?
A "trick" to understanding this example is to add printlns
(and then throws Exception)
Which shows you that the try block is run first as always. The catch block comes next since the try block throws an exception. Then the finally block runs last as always. Since it throws an exception, you get that one instead of the one from the catch block. But all three run!
Your correspondent has misunderstood what you said. Yes, control goes from line 2→3→4 (first code block) to the catch. That causes an unchecked exception to be thrown, but it is not the same object as in line 2. Then the finally is executed later; the plain simple Exception from line 6 supersedes the unchecked exception in line 4 (I am sure supersedes isn't quite the right word).
Maybe you could regard it as,
1: The execution starts in the try.
2: The catch is only executed if an appropriate exception is thrown in the try.
3: The finally is always executed, and always last.
posted 1 month ago
If the finally follows a catch, it is also after the try. It doesn't say anything about directly after anywhere, does it?