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 trial

C#

C# Try/Catch Question for C# Objects course

Can anyone provide me with the answer to the following Code Challenge. I'm pulling my hair out because of it.

https://teamtreehouse.com/library/c-objects/inheritance/catching-exceptions-2

Many thanks in advance!

2 Answers

Steven Parker
Steven Parker
231,269 Points

May I suggest that you temporarily skip this challenge and continue on to the end of this stage, and then return and try the challenge again. The additional instruction and examples in the next few lessons should make what's needed for this task much clearer.

Hi Steven,

Thanks for your answer. I completed this stage, but this hasn't helped me resolve the question. The bit that's confusing me is this element of the task: "wrap the testing logic with a try/catch".

Using the below as a standard Try/Catch template, how do I implement if (value < 0 || value > 20) in place of DoSomething()?

    try
    {
        DoSomething();
    }
    catch(System.Exception ex)
    {
    }

i.e. how do I make this work?:

    try
    {
        if (value < 0 || value > 20) {
        ...
        }
    }
    catch(System.Exception ex)
    {
    }

Many thanks,

Richard

Steven Parker
Steven Parker
231,269 Points

Looks like you were almost there. The "wrap" suggestion means put the entire logic inside the "try" block:

try {
    if (value < 0 || value > 20)
    {
        throw new System.Exception();
    }
    Console.WriteLine(string.Format("You entered {0}",value));
}
catch(System.Exception ex)
{
    // then you just need to issue the error message here
}

Ah! I had assumed it meant for us to remove the throw new System.Exception(); line during the 'wrapping', hence my confusion on how to actually force it!

Many thanks!