Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialD Elis
13,571 PointsDoes anyone know how this Exception message was generated from Game.cs?
I am a little confused about how in this example... Console.WriteLine(ex.Message); … how was ex.Message able to genereate the string message from MapLocation.cs
What I'm mostly confused about is where we find the mysterious 'Message' …. from 'ex.Message' Console.WriteLine(); above …. I don't see 'Message' anywhere in any of our files.
2 Answers
Steven Parker
231,236 PointsThe "Message" property is part of the exception object that is created by the system when an error occurs or when you perform a "throw". The argument passed to "throw" gets loaded into the "Message" property by the system. This property can then be accessed when the exception is caught in the parameter "ex".
For more details, see the MSDN page for Exception.Message.
Stephen Cole
Courses Plus Student 15,809 PointsThere are a number of properties returned when an exception is returned.
Message
is the text from the constructor we created.
I'm guessing that string interpolation was not yet a thing when this video was first created. Here's my code.
namespace TreehouseDefense
{
class MapLocation : Point
{
public MapLocation(int x, int y, Map map) : base(x, y)
{
if (!map.OnMap(this))
{
throw new System.Exception($"({x}, {y}) is outside of the map's boundaries.");
}
}
}
}
The Message
returned in my code is $"({x}, {y}) is outside of the map's boundaries."
This gives me a chance to return a message that has meaning and/or context.
Here's a link with more information about the other properties returned: https://docs.microsoft.com/en-us/dotnet/standard/exceptions/exception-class-and-properties
Roger Sullivan
10,992 PointsRoger Sullivan
10,992 PointsI don’t remember exactly where you are here, but the honest answer here is it depends.
Some exceptions are thrown automatically by the .NET Framework's common language runtime (CLR) when basic operations fail. I’m guessing since you don’t know were they came from you didn’t create them. Creating you own exceptions will probably be dealt with later on.
Check out the MSDN for more info, https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/