Game Development Reference
In-Depth Information
What we did not yet address in our file reading methods, is what to do if some-
thing goes wrong. For example, what happens when one of the lines in the text
file has a different length? And what if the file cannot be found? These are things
that are impossible for the compiler to detect beforehand, so this will not gener-
ate a compiler error. There is a way of dealing with these issues by using excep-
tions .
25.8 Exceptions
25.8.1 Dealing with Errors
When you call a method, it is possible that due to some unforeseen circumstances,
the method cannot be executed. For example, the player of your game has the ex-
cellent idea to disable the network adapter during the setup of an on-line game. Or:
because of a virus, some files that you expected to be there are suddenly missing.
There are several ways of dealing with this. One way is to do nothing and let the
program crash. This is a very cheap solution for the game developer (initially at
least ...), but it does not result in a very robust game which will in turn surely af-
fect sales negatively. A very common way of dealing with these kinds of errors is
by handling exceptions . An exception is thrown by a method, and the caller of the
method will have to deal with it.
An example of a method that throws an exception is the static method Parse that
is available in types such as int and double . This method throws an exception if the
string to be parsed contains something else than numbers (or a minus sign and in the
case of double .Parse , a decimal point or the E character).
25.8.2 The try - catch Instruction
You could try to avoid exceptions by checking beforehand if all the conditions are
satisfied. In the case of int .Parse , this means checking if the string consists only of
numbers/signs. However, you would be doing double the work, since this is also
checked in int .Parse . Better is to react to the exception. This is done using the try -
catch -instruction. The method call that may throw an exception is put inside the
body of a try -instruction. In the case that there is an exception, the program contin-
ues in the body of the catch -part. If there is no exception, then the catch -body is not
executed. For example:
try
{
n= int .Parse(s);
}
Search WWH ::




Custom Search