IndexOutOfBoundsException won't catch


I’m having trouble getting the cat ch statement below to catch when index input is larger than array. Thanks for any pointers :slight_smile:

	String [] firstNames = { "Onassis", "Petros", "Ulysses", "Hector", "Agamemnon", "Helen", "Agatha", "Ajax", "Amazonian", "Cretan", "Thracian" };
	int arrayLength = firstNames.length; 
	//Name at integer position
	int intPosition = Integer.parseInt( JOptionPane.showInputDialog("Enter an integer position)") );
	for ( int i= 0 ; i < arrayLength ; ++i)
			if (intPosition == i)
				System.out.println( firstNames[i] );	
		catch(ArrayIndexOutOfBoundsException error)



an error won’t occur, i can’t get out of range.

Why would you want to use a loop here? Simple compare arrayLength with intPosition to determine if the user entered integer is out of range


Thank you. After focussing on the wrong thing, I took a break, had a cuppa, and with your assistance it makes sense, it had no function :slight_smile:

Thanks again


tunnel vision can be a tricky thing indeed

yea, given i can’t get out of range/index, i == intPosition will never evaluate to true when intPosition is out of range/index, so you never access do firstNames[i] with i out of bounds.

still, you could consider both if and try/catch for catching out of bound intPosition. But please tell me you got rid of the loop?


the loop has gone into the TWILIGHT ZONE!
thanks a million for following up


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.