IndexOutOfBoundsException won't catch


#1

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)
	{
		try
		{
			if (intPosition == i)
			{
				System.out.println( firstNames[i] );	
			}
		}
		catch(ArrayIndexOutOfBoundsException error)
		{
				System.out.println("Error");
		}
	}
}

}


#2

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


#3

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


#4

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?


#5

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


#6

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