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:
Why does the order of the output change between the
catch
, andfinally
blocks? From reading posts such as this, I would expect them to output in the same order with each execution.Notice in the example output One that the line break is missing between the sentences. Why?
Thank you for your help.