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# Basics (Retired) Perfect Final

Confused about what to put inside the try/catch areas

I don't understand why this part goes inside the try area:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int count = int.Parse(input);

To me, the input is when you would read what the user inputs, and then if it's valid, THEN you go to the try area. If it isn't valid, then you go to the catch. Clearly I'm wrong about this but just seeing if anyone can help me understand why.

1 Answer

Kevin Gates
Kevin Gates
15,053 Points

Hi there,

So Try-Catch is a clever way to test out code that may fail. So looking at this:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
int count = int.Parse(input);

There is one area that code go wrong, and it's the Parsing method. Why? Because the input will be a string, and if the user writes "Book" instead of a number, the application will fail.

Therefore, you are better served by this:

Console.Write("Enter the number of times to print \"Yay!\": ");
string input = Console.ReadLine();
try
{
   int count = int.Parse(input);
}
catch (error)
{
   Console.WriteLine(error);
}

Again, the reason is that the code likely to fail is the parse method. Therefore you want to "try" that. And if it fails, you want to "catch" the error, so it fails gracefully.

That does make sense, thank you. I have to change the way I think about try/catch. In my mind, I've thought if it ask an if/else. (e.g., if it works, do this (try), if it doesn't work do that (catch).

Kevin Gates
Kevin Gates
15,053 Points

Hi Christian,

The best way to approach If/Else is if you get different working (non-errors) options returned and you're trying to figure out if you get A, do path-A, and if you get B, do Path B.

Try/ Catch is more if you get A-Z, great. If it blows up and you don't get A-Z back, send this error and perform this action.