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# Objects Inheritance Throwing Exceptions

Minh Cao
Minh Cao
1,792 Points

HI there, I have tried many permutations of the code but perhaps I did not understood what the task require of me.

I have tried many permutation of the program but none seems to work:

  • Print out line when exception is thrown
  • Print out line then check value

Does the task require me to:

  • throw an exception when the value is within 0 and 20?
Program.cs
    int value = int.Parse(Console.ReadLine());
try
{
    Console.WriteLine(string.Format("You entered {0}",value));  
    if ((value < 0) || (value > 20))
    {
        throw new System.Exception();   
    }
}
catch(Exception)
{

}

1 Answer

andren
andren
28,558 Points

The problem is that you are overthinking what the challenge actually actually wants. The instructions are to:

Throw System.Exception if the value is outside of the range.

And that is literally all you have to do to complete the challenge, throw the exception if the value is outside the range specified. Where you place the code that checks the value is not important, what is important is that you literally just throw an exception if the value is out of range.

The reason why your code is marked as invalid is that the challenge is not setup for you to catch the exception that is raised, you are only meant to throw it. The challenge checker that runs your code to verify that it is written properly is actually looking for that exception being thrown to mark your code as correct. If you catch the exception in your code then the exception will never reach the challenge checker which runs your code.

If you remove the try/catch block but keep the code you have written inside it then your code will pass. Like this:

int value = int.Parse(Console.ReadLine());

Console.WriteLine(string.Format("You entered {0}",value));  
if ((value < 0) || (value > 20))
{
    throw new System.Exception();   
}
Minh Cao
Minh Cao
1,792 Points

Cheers Andren, That really clarifies things