2

Came accross this weird issue yesterday. Can't seem to find any logical explanation in the java spec for the following...

public class Program {

    public static void main(String[] args) {
        int i = 0;

        try {
            bork(i++);
        } catch (Exception e) {
        }
        System.out.println(i);
    }

    private static void bork(int i) {
        throw new RuntimeException();
    }

}

One would think post-increment would not happen because bork throws the exception, but it does!

What is the explanation for this behavior?

1 Answers1

3

The i++ operation is invoked, before the method bork() is invoked. That's the reason why it's still incremented.

So:

  1. i++ is invoked.
  2. As a result it returns the state of i before the increment.
  3. At the same time the actual state of i is incremented. So the value of i is now 1.
  4. bork(0) is invoked.
  5. The exception is thrown.
  6. The exception is handled (by doing nothing)
  7. The current state of i is printed which is equal to 1.
Rozart
  • 1,668
  • 14
  • 27
  • That's exactly what I saw in the bytecode as well! I noticed aload, iinc and then the invoke. It's just really counter intuitive. – Jan De Kock Oct 18 '19 at 14:42
  • https://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept - Maybe this topic can give you more insight. Also if you consider my answer helpful, please mark it at as a correct one. :) – Rozart Oct 18 '19 at 14:47