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

i believe i did it right but it still shows me that i did a mistake

Is there any mistake in here ?

Program.cs
try 
{
    int value = int.Parse(Console.ReadLine());
Console.WriteLine(string.Format("You entered {0}",value));

     if (!(value > 0 && value < 20)) 
     {
         throw new Exception();
     }
}
catch (Exception)
{
     Console.WriteLine("value out of the range");
}

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

There's a slight difference between the following two expressions.

!(value > 0 && value < 20) // true for 0 and 20

value < 0 || value > 20 // false for 0 and 20

!(value >= 0 && value <= 20) // false for 0 and 20

You also don't want to catch the exception. The program that grades this challenge is expecting to catch it, so you have to let it get thrown upwards. All you need to do is similar to what I've done below (but with the correct expression)

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

Console.WriteLine(string.Format("You entered {0}",value));

if ( /* test value here */ ) 
{
  throw new System.Exception();
}

ah ok , i got it ,

about the first if (condition) i believe i got it very well .

about throw , i thought that i should use throw only inside try/catch

thank you

Samuel Ferree
Samuel Ferree
31,722 Points

in real world applications. You should try to catch your exceptions. However, in order for this challenge to pass correctly, you need to let the challenge environment catch the exception.