2

Here is my simple test code:

class Scratch { public static void main(String[] args) { try { System.out.println("Line 1"); throw new RuntimeException(); } catch (RuntimeException e) { e.printStackTrace(); } finally { System.out.println("Line 2"); } } } 

After running I'll get this:

Line 1 Line 2 java.lang.RuntimeException at Scratch.main(scratch_4.java:5) Process finished with exit code 0 

I thought that "finally" code must be executed at last, but it's not. What is the reason?

4
  • 1
    I think that the finally just is defined to execute before the code in catch. I'd have to look that up in the language spec though to be sure. Commented Sep 6, 2021 at 15:31
  • 2
    @markspace: No, it's definitely executed after the catch block. Commented Sep 6, 2021 at 15:32
  • 1
    I accept the correction! I'll leave my comment up though since I think it illustrates a possible misunderstanding. Commented Sep 6, 2021 at 15:38
  • @markspace I was going to say that the keyword finally should make it clear that it's the last thing to happen; but then I spotted that the Oracle tutorial says "The finally block always executes when the try block exits.", which is a pretty misleading statement. Like JonSkeet says: it's definitely executed after the catch, if a matching exception was thrown by the try. Commented Sep 7, 2021 at 8:14

1 Answer 1

5

By default, printStackTrace prints to System.err, whereas you're writing to System.out. So you're writing to two different streams, and in your particular case it looks like the buffering involved has switched the output order from the actual execution order.

If you either write to a single stream (e.g. using System.err.println or calling e.printStackTrace(System.out)) or change your catch block to just write to System.out like your other lines do, you'll see the order of try => catch => finally.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.