Out of Bounds and One off Errors

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Arrays


Introduction

This section will cover 'Out of Bounds' errors and 'One Off' errors. A brief introduction to these concepts as well as their use and significance will be covered below.

Note: A One Off exception is a subclass of an Out of Bounds error.


Out of Bounds Error

An Out of Bounds error is one in which the program tries to access a location in the array that does not exist. For example, in an array with 20 data locations, trying to select the 21st would cause an Out of Bounds error.

The following example displays code that will fail because of the Out of Bounds error:

 int position = 20;

String array[] = new String[10];

array[position] = “Hello World”; 

This will fail because the value of ‘position’ is outside the array’s boundaries. There is no way to correct this error if the value being used (in this example's case: ‘position’) is not known ahead of time. You can, however, prevent the error from occurring by checking the variable (in this case: ‘position’) before applying it.

 String position = 20;
String array[] = new String[10];

if(position < array.length && position >= 0)
{
    array[position] = “Hello World”;
}
else
{
    System.out.println(“Error: value in ‘position’ (” + position + “) exceeds size of array ‘array’ (” + array.length + “)”);
} 

This will result in an error message being printing rather than the operation being performed, causing the program to fail. This will also work in any of your programs where the value being checked is not known ahead of time.


One off Error

A One off error is a form of an Out of Bounds error. The distinguishing feature of a One off error is that they occur as a result of an improper loop. The term ‘One off’ means that the either the loop results in the accessing of a location one over the array’s length (if it is an incremented loop) or one below (in the event of a decremented loop).


The following example displays code that will fail because of the One off error:

 int array[] = new int[10];

for(int i = 0; i <= array.length; i++)
{
    array[i] = i;
} 

This fails because the loop will count from 0 to 10; however, arrays are 0-relative (the very first location of the array is 0 and the last is the ‘defined length’ – 1) so the last valid data location in this case is 9. You can solve this problem by stopping the loop one element before the length by changing the condition to ‘i < array.length’.

Summary

In this section you have seen what happens when you try to insert an element into a location not in the array, how to check the boundary of an array before attempting to access an element, and what happens when you try to access the last element of the array without implementing 'length-1'. In the next section you will how to Process Arrays (using for loops).

Previous Page: Entering and Using Array Elements Next Page: Processing Arrays (using for loops)