Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array out of bond 2

Status
Not open for further replies.

Kicket

Technical User
Jun 15, 2002
155
US
I have this array: Array[10][10]

var=Array[-1][10][/green]
it will return out of bond error, right?
is there away to make an error handler? like if var=Array[-1][10] out of bond, i will do so and so..

?

ff
 
try{
//your code here
} catch (IndexOutOfBoundsException e){

// do something here
}

 
here's what i did

try{
//mycode
}
catch (IndexOutOfBoundsException e)
{
System.out.print(" out ");
}
}

but it will still return an IndexOutOfBondsException: -1
without excute the code System.out.print
ff
 
my bad,
it did not return an IndexOutOfBondsException
but it didn't excute the code below either hehe
ff
 
Hi Kicket,
-but it didn't excute the code below either
Yes, it will. I tested it out and found the error is caught successully and prints out. Here is the tester class:
Code:
public class IOBTester {
	
	public static void main (String[] args) {
		
		int [] [] array = new int [10] [10];

		try	{
			array [10] [10] = 5;	
		}
		catch (ArrayIndexOutOfBoundsException exception) {
			System.out.println (exception);
		}
	}
}
In any case, this is not a good way to handle errors with arrays. Exceptions are not to be used lightly as they interrupt the normal flow of a program. A better way to check for errors with arrays is to make sure that the indices you are using are at least 0 and less than the arrays length, like this:
Code:
public class IOBTester {
	
	public static void main (String[] args) {
		
		int [] array = new int [10];

		int index = 10;

		if (index >= 0 && index < array.length) {
			array [index] = 5;	
		}
		else {
			System.out.println (&quot;Array out of Bounds&quot;);
		}
	}
}
Some might diagree with me on this, but over the years I have found that checking for the error is usually easier and in most cases faster than using
Code:
try {}catch (Exception) {}
to have the work done for me. It is certainly faster than having an Exception generated and having your program interrupted. [smile]

Hope this Helps,
MarsChelios
 
i see.
thanks for the help

ff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top