Just don't throw an exception and then:
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { if (i % 2 == 0) { System.out.println("i = " + i); } }
Or throw it away and catch it inside the loop, not outside (but I see no reason to throw an exception in this trivial example):
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < arr.length; i++) { try { if (i % 2 == 0) { System.out.println("i = " + i); throw new Exception(); } } catch (Exception e) { System.err.println("An exception was thrown"); } }
Side note: See how code is much easier to read when it is indented correctly and contains spaces around statements.
source share