Exceptions

Code can compile, but still contain logical errors. These are things that often cannot be reliably checked at runtime because they require data that is only available at runtime (such as depending on a network connection, processing data based on modifable settings, or processing user input). There are many forms of error that can occour, and we need to be careful about checking user input. Here are some common types of errors which can occour at runtime.

Code can compile, but still contain logical errors. These are things that often cannot be reliably checked at runtime because they require data that is only available at runtime (such as depending on a network connection, processing data based on modifable settings, or processing user input). There are many forms of error that can occour, and we need to be careful about checking user input. Here are some common types of errors which can occour at runtime.

Index Out Of Bounds

One of the most common excepitons you are likely to encounter is an index out of bounds exception. These often occour because you are trying to access elements which are outside of the supported range.

If an array (or list) contains 5 items, then the items will be numbers 0,1,2,3, and 4. There is no item 5, and trying to access any element at index 5 or higher will result in an error.

int[] myArray[5];
int lastValue = myArray[5];

The second line in this case is out of bounds because the last element is actually 4, and not 5.

For Loops

The check performed by < is exclusive, which is what you want when looping over values. Consider the following code snippet:

int[] squares[10];
for (int i=0; i<10; i++) {
	squares[i] = i * i;
}

This code is correct, but will store the squares between 0 and 9 (not 10), as we use zero-based indexing. If we wanted to also include 10, we would need to either:

  • Calculate the square as (i + 1) + (i + 1), which would mean that squares[0] actually contained 1*1
  • Make the array size 11, and count to 11 in the for loop, by adjusting the condition

The second option probably makes more intuative sense for a reader, but does mean we’re also going to store 0 squared, which is a reasonbly meaningless thing to store.

NullReferenceException

The concept of null is a variable that does not currently store anything. It can be useful as a sential value, but you may encouter it if you try to use a variable which is not initialised.

Consider the following code snippet:

Object myThing = null;
if ( myValue > 10 ){
	myThing = "Hello, World";
} else if ( myValue <= 10 ) {
	myThing = "Goodbye, World";
}

What happens if myThing is negative?


Last updated 0001-01-01

Graduation Cap Book Open book GitHub Info chevron-right Sticky Note chevron-left Puzzle Piece Square Lightbulb Video Exclamation Triangle Globe