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

Tony Lawrence
Tony Lawrence
3,056 Points

Challenge Keeps asking me if I added Catch Block to capture Thrown Exceptions.

I'm having trouble trying to figure out what the challenge is trying to hint to me every time I hit Recheck Work. It keeps asking if I added an Catch block to Capture Thrown Exceptions.

This is what I have written out so far:

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

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

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

I've tried moving the Try/Catch blocks next to the If statement, but it gives me different errors. I get the feeling I'm on the right track and there is just one last thing to do, but I'm not sure what it's looking for, since these challenges can sometimes be picky with what you type up.

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));
try 
{
   value = 24;
}
catch(Exception)
{
    Console.WriteLine ("Value is out of bounds!");
}

1 Answer

Steven Parker
Steven Parker
231,268 Points

Be sure to put your try block around the code that might cause an exception.

You can be pretty sure that assigning a literal value to a variable of the appropriate type will never throw an exception. And setting value this way isn't part of the challenge anyway.

When they say "Wrap the testing logic...", they are referring to the place where the value is tested and when not in a certain range, an explicit throw is called. It is this portion of the code (and perhaps the following WriteLine) that should be enclosed in (not just placed next to) the try block, with the catch following.