Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Inheritance Exception Messages

Does 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.

I 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/

2 Answers

Steven Parker
Steven Parker
221,297 Points

The "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
PLUS
Stephen Cole
Courses Plus Student 15,592 Points

There 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