new to StackOverFlow and fairly new to Java. Been programming in C prior to this and am trying to get the foundations of Java.
Just a bit confused about the following code:
public class Exercise5 {
private static int[] ia = new int[3];
static int x = 5;
public static void main(String[] args) {
while(true) {
try {
ia[x] = 1;
System.out.println(ia[x]);
break;
} catch(ArrayIndexOutOfBoundsException e) {
System.err.println(
"Caught ArrayIndexOutOfBoundsException");
e.printStackTrace();
x--;
} finally {
System.out.println("Are we done yet?");
}
}
System.out.println("Now, we're done.");
}
}
I am still trying to get my head around the try,catch and finally blocks. What I do not understand is in this code the program only runs until the first instance that a non exception occurs happens and then it exits the while loop.
My understanding is that the while loop will run until you run out of memory so can someone please explain how the code exits the while loop on the first instance of non exception.
Thank you!
Marco
First,
xis equals to 5 and then program goes to thewhileloop. Since 5 is greater than the size of the array, it will give exception and go to the exception block. Here,xwill be decreased and run into thewhileloop again. Untilxreaches to 2, there is no exception anymore; therefore, it can reach thebreakline. So, program can exit thewhileloop and finish