Reputation: 51
I am doing a project with a 3D array where i need to test every single cell around one cell. If the cell is on the edge of the array however, testing a cell outside of the array will throw an out of bounds exception. I want to fix this with a catch statement, but writing a try and catch to test each block would require a very large amount of code (there are 8 cells surrounding a cell in a 3D array). Is there a way to catch many "tries" with only one catch, and then to continue where it left off? For example, if the tester method tests an out of bounds cell, i need it to not just catch, but continue testing other cells.
Upvotes: 1
Views: 1758
Reputation: 24548
I can only guess: Your code probably has a whole bunch of different loops, but the core of every loop is very similar. Just use the same method inside every loop:
for ... x ...
do(x);
for ... x ...
do(x);
for ... x ...
do(x);
// ...
void do(... x)
{
try
{
// code here
}
catch ...
// ...
}
Also, please note that you should not implement your in-bounds
check by catching exceptions. That is very bad design. Make sure, your array accesses are always in-bounds. If the loop condition itself cannot attain that goal (because your array is, for example, not a uniform grid), add further if
statements.
Upvotes: 4
Reputation: 354
I believe you will need a loop for testing the cells surrounding another cell. What you can do is, inside the loop write a try...catch statement and after it give a continue
for (/*loop conditions*/) {
try
{
//your code here
}
catch (/*catch the IndexOutOfBoundsException here*/)
{//write any action or message you need to have here}
continue;
}
this way, your loop will run completely irrespective of any IndexOutOfBounds exception(s) thrown.
Upvotes: 0
Reputation: 751
Alternatively you can put an if statement checking whether you are still in bounds or not, if yes access the cell, otherwise do not.
Upvotes: 1
Reputation: 26185
An alternative solution is to put a layer of guard cells around the cells you need to test. Only test the neighbors of actual cells, but edge cells will see the guard cells instead of getting an out-of-bounds exception.
Upvotes: 1