Game Development Reference
In-Depth Information
catch (FormatException e)
{
spriteBatch.DrawString(s + "is not a number", Vector2.Zero, Color.Red);
}
catch (OverflowException e)
{
spriteBatch.DrawString(s + "is too big", Vector2.Zero, Color.Red);
}
finally
{
spriteBatch.DrawString("Program finished", Vector2.Zero, Color.White);
}
25.8.3 Throwing Your Own Exceptions
You can make your own code more robust by checking if some conditions hold, and
throwing an exception if they do not. For example, if we are loading a level from a
file and we notice that not all the lines in the file have the same length, we can throw
an exception:
if (line.Length != width)
throw new FormatException("The length of the lines is different.");
Somewhere else in the program this exception can then be caught and dealt with
(for example, by showing the player a message that the level file is corrupted). By
using exceptions in your game, and properly handling them, your game will become
more robust. If you plan to deploy your game commercially, it is crucial that you
deal with possible exceptions in your program, so that your game can stand up to
the abuse of the player, as well as deal with any unforeseen circumstances. Both the
try - catch -instruction as well as the throw -instruction as part of the instruction syntax
diagram:
 
Search WWH ::




Custom Search