0

I'm working on a legacy system and to simulate some behavior I tried simpler pieces of code, like this one, to understand exception handling (the legacy system uses lots of user exceptions). I know throwing exceptions at finally block is undesired, but my goal was to understand current behavior, not develop some improvements.

public class ExceptionTest {

  public static void loopUntil10() {
      for (int i = 0; i < 10; i++) {
          if (i == 7) {
              System.out.println("7!");
              throw new NullPointerException("7");
          }
          if (i == 8)
              System.out.println("8");
      }
  }

  @SuppressWarnings("finally")
  public static void main(String[] args) {
      try {
          System.out.println("1");
          ExceptionTest.loopUntil10();
          throw new NullPointerException("2");
      } catch (Exception e) {
          System.out.println("3");
          throw new NullPointerException("4");
      } finally {
          System.out.println("5");
          throw new NullPointerException("6");
      }
  }
}

With this I thought it should print

  • 1followed by 7!, I think this was no surprise
  • since NPE("7") will be thrown, execution would go to catch block, printing 3 and throwing NPE("4")
  • after catch block finishes, finally block would print 5 and throw NPE("6")

Although I don't know what happens to exceptions 7 and 4,it prints like planned:

1
7!
3
5
Exception in thread "main" java.lang.NullPointerException: 6
    at ExceptionTest.main(ExceptionTest.java:26)

But sometimes it gets weird:

enter image description here enter image description here

Is this a weird Eclipse behavior ou some Java Exception concept I'm missing? Are 7 and 4 exceptions lost? I mean, there's any trace they were called sometime?

rado
  • 5,720
  • 5
  • 29
  • 51
  • 2
    There is no synchronization between standard error and standard output printing. In eclipse, red is standard error; black is standard output. – Andy Turner Nov 06 '18 at 13:10
  • 1
    The `NullPointerException("7")` is catched with your exception handler (and therefore handled). The `NullPointerException("4")` is lost because during processing of the `finally` clause the `NullPointerException("6")` is thrown. – Thomas Kläger Nov 06 '18 at 13:36

0 Answers0