Throwing Exception
We have to prepare if user doesn't give a valid coordinate for MapLocation. So, we could throw the exception and asking for another input.
The best place to put our validation is in the constructor in MapLocation class. Because it is called when object is called before created.
class MapLocation : Point
{
public MapLocation(int x, int y, Map map) : base(x, y)
{
if (!map.onMap(this))
{
throw new Exception();
}
}
}
this
refers to method that being called. Now, our constructor need Map as an input. If the map is not fulfill the onMap
method, it will throw the exception and the object couldn't be created yet.
Meanwhile, In the Game
class, we have to catch the exception thrown from MapLocation
class.
class Game
{
static void Main(string[] args)
{
Map map = new Map(8, 5);
try
{
MapLocation mapLoc = new MapLocation(8, 5, map);
}
catch (Exception)
{
Console.WriteLine("coordinate out of range");
}
Console.Read();
}
}