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

I tried but don't know what to do

Here's how I wrote the code. Now wrap the testing logic with a try/catch and write the message "Value is out of bounds!" to the console if the exception is caught.

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

if (value < 0 || value > 20)
{
    throw new System.Exception();
}

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

4 Answers

Hi Vedang, You just need to wrap a 'try' around the items you want to check. The exception gets thrown and the try fails if the the value is < 0 and > 20.

The catch is then executed, writing the line 'out of bounds'.

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

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

thank you Damien Watson

Did you mean to put the ''e" in catch(Exception e) ? I put it without the "e" and it passed.

int value = int.Parse(Console.ReadLine());
try
{
    if (value < 0 || value > 20)
    {    
        throw new System.Exception();
    }

}
catch(Exception)
{
    Console.WriteLine("Value is out of bounds!");
}
Console.WriteLine(string.Format("You entered {0}", value));


Here you go!

in catch why did we add e with the exception is it a variable to store the error message

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

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