Possible Exception Example
Suppose we have this code:
int [] OurArray = new int[6];
int I = 0;
String S;
using (StreamReader SR = new StreamReader("OurData.txt")
{
S = SR.ReadLine();
while (S != null)
{
OurArray[I] = (int) ConverttoInt64(S);
I++;
S = SR.ReadLine();
}
}
What could happen with this code?
- We could have a FileNotFoundException if "OurData.txt" does not exist.
- We could have an UnAuthorizedAccessException if the file does exist
but we do not have permission to read it.
- We could have an IndexOutOfRangeException if the index I eventually
reaches the value 6.
- We could have a FormatException if S does not match the pattern needed
to convert it to an Int64.
- We could have an OverFlowException if the integer represented in S is
too large to be an Int64.
- We could have an OverflowException if the Int64 value is too large to
fit into Int32.
Thus, in theory we could have 5 or 6 catch blocks. If we want to use the
catch blocks, we will need to have some try blocks as well.
Could we avoid the problems involved? Yes, probably we could:
- We could use the File.Exists method, which will return true if "OurData.txt"
exists and we have permission to read it.
- We could code an explicit test on the value of I:
while (I < 6 && S != null)
- We could use the TryParse method of the Int64 class to convert S to Int64:
public static bool TryParse(String S, out long Result)
This will return true if the operation succeeds and false if the string cannot be
converted. It does not throw a FormatException.
- We could do the same with the TryParse method of Int32 first to see if
the explicit cast is going to work, or we could first use Int64.TryParse
and then, if it succeeded, we could compare the value to the predefined
values Int32.MinValue and Int32.MaxValue.