0

While trying to learn how to handle exceptions in Java, I noticed this:

int[] intArray = new int[4];

void eDemoI(int i) {
    try {
        int myInt = intArray[i];
    } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println("Your index was out of bounds.");
    } finally {
        System.out.println("This line always prints.");
    }
}

public static void main(String[] args) {
    ExceptionHandlingPractice P = new ExceptionHandlingPractice();
    P.eDemoI(5);
}

Here is where I get confused.

If I run this a few times back-to-back with same input (in this case, 5), I seem to randomly get one of three outputs:

One:
Your index was out of bounds.This line always prints.

Two:
Your index was out of bounds. This line always prints.

Three:
This line always prints. Your index was out of bounds.

Which brings me these questions:

  1. Why does the order of the output change between the catch, and finally blocks? From reading posts such as this, I would expect them to output in the same order with each execution.

  2. Notice in the example output One that the line break is missing between the sentences. Why?

Thank you for your help.

Jake Stokes
  • 445
  • 1
  • 5
  • 17
  • 2
    Why do you think `err` and `out` are synced against each other? In other words: use just one and you'll get stable results. – Tom Aug 01 '17 at 11:39
  • 1
    Downvoter: The issue of syncing between streams is **not obvious**, nor is the linked question an obvious thing to find if you're thinking about exceptions, not streams. The question is clear, describes exactly what the OP is doing, quotes the necessary code (and not too much code), etc. It's a good question. Let's not overdo the downvoting. – T.J. Crowder Aug 01 '17 at 11:42
  • Thanks Tom (and T.J.). I have intuitively assumed that in this case, given that they are in separate blocks of code, and that what I have read on the forums indicates that the blocks are executed in the order they are reached, that it would indeed print in that order. Also having had a quick read of the post you have linked, Tom, I understand from this that it should still print in the order I was expecting, as .println should flush the respective stream. Is there something else I should also look at to understand why this is not the case? Perhaps relevant to my second question? – Jake Stokes Aug 01 '17 at 11:51
  • They flush themself if that is implemented that way. You're using an IDE (at least I guess so) and they have own consoles with own caches. So either test your code on your OS console (Windows or Linux) or reduce the cache in the settings of your IDE. – Tom Aug 01 '17 at 12:04

0 Answers0