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 Catching Exceptions

I entered "2". I expected "You entered 2" but got "Value is out of bounds!" instead.

I need help with this problem

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

try
{
    if (value > 0 || value < 20)
{
throw new System.Exception();
}
else
{
        Console.WriteLine(string.Format("You entered {0}",value));
    }
}
catch (Exception e)
{
    Console.WriteLine("Value is out of bounds!");
}

1 Answer

Hey so there are a few things here to look at. :) What you're currently saying in your if statement is

if the value is more than 0, or the value is less than 20, throw an exception

This basically means, any value you input will throw an exception because all values are either greater than 0 OR less than 20.

There are a few ways to fix this, depending on how you want to approach it. You could change your code to say

if the value is more than 0 AND the value is less than 20, Console.Writeline($"You entered {value}"), else throw exception

Or you could change the direction of your greater/less than symbols. So instead you'd be saying:

if the value is less than 0 OR the value is greater than 20, throw new exception

Hopefully that makes sense. :) Keep at it!