Post increment behavior when throwing an exception

Viewed 98

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 Answers

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.
Related