They are different kind of errors, but resemble in a way that they both tell you that you are trying to
reference an object that
doesn't exist.
NullReferenceException[^]
This exception means that the object being used or operated on, doesn't exist. Possible candidates are type-mismatch (
Object reference not set to an instance of object) and sometimes when you declare a variable but forget to initialize it with a
valid value. It can be handled using the try catch block, but good way to handle it is to initialize the variables and to make sure that they are not
null
; that they
do exist in the memory.
My blog post about
null
exceptions:
What is a null error in code Execution[
^]
IndexOutOfBoundsException
Doesn't exist in .NET framework, it is a Java based exception. In .NET framework there is a
IndexOutOfRangeException
[
^]. Which means that you are trying to reference an object that doesn't exist in the limit of the array (or collection).
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(arr[10]);
It can be minimize by using the
try catch
, but the good way to handle it is to make sure that you do not reference an object out side the bounds. Always check the count of the objects in the collection and then perform respectively.
int[] arr = { 1, 2, 3, 4, 5 };
if(arr.Length == 5) {
Console.WriteLine(arr[4]);
}
It is never good way to let the framework always handle the exceptions, you need to know what you are doing. Although try catch is a good way to ignore unexpected application breakage, but it is not a good way to develop the software. You need to handle the problems yourself or at least know where exceptions are going to be raised to handle the scenarios.
if...else
is a good candidate.