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.
4 Answers
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.
Comments
Alternatively you can put an if statement checking whether you are still in bounds or not, if yes access the cell, otherwise do not.
1 Comment
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.